I want to copy sql server table in sharepoint 2010list, I know that Business Data Connectivity Service (BDC) might do it, but I have some problems and it doesn't work, so I want to do it programmatically. Any Ideas ?
1 Answer
It's a simple example to retrieve Records from SQLdatabase table to SharePoint list
Create a function to get your data from SQL server and return it to a data table.
// your method to pull data from database to datatable public DataTable GetDatafromSQL() { DataTable dataTable = new DataTable(); string connString = @"your connection string here"; string query = "select * from table"; SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand(query, conn); conn.Open(); // create data adapter SqlDataAdapter da = new SqlDataAdapter(cmd); // this will query your database and return the result to your datatable da.Fill(dataTable); conn.Close(); da.Dispose(); return dataTable; }Create a function that loop for every item at the retrieved SQL data table and adds it to list.
void binditems() { DataTable dt = new DataTable(); dt= GetDatafromSQL(); using (SPSite oSite=new SPSite("http://mysharepoint")) { using (SPWeb oWeb=oSite.RootWeb) { SPList oList = oWeb.Lists["Test"]; foreach (DataRow row in dt.Rows) // Loop over the rows. { SPListItem oSPListItem = oList.Items.Add(); oSPListItem["Title"] = dr["Title"].ToString(); oSPListItem.Update(); } } } }
Read the Function binditems(), to can bind the data from SQL to List
Note : don't forget to include this namespaces using System.Data.SqlClient; using Microsoft.SharePoint;
Check also How to achieve this in a windows application Using SharePoint Server Object Model
Check also Copy items from sql database table to SharePoint list
-
it works, thankx again, last question, if I want to edit from sharepoint list , and see it in sql table , what should I do ?BKChedlia– BKChedlia2016-09-21 14:31:20 +00:00Commented Sep 21, 2016 at 14:31
-
Dear @BKChedlia in this case, you should create Event receiver on item update via visual studio , then get the related item in sql table then update item with Update sql statement. please tell me if you need a reference to do this ,2016-09-21 14:35:58 +00:00Commented Sep 21, 2016 at 14:35
-
I will try the event receiver, but you can please help me with a reference or exemple . thankx againBKChedlia– BKChedlia2016-09-22 06:57:37 +00:00Commented Sep 22, 2016 at 6:57
-
I noticed a problem, when I call my code binditems() from the page load (I put it in webpart), it repeat the items each time I hit f5BKChedlia– BKChedlia2016-09-22 07:59:11 +00:00Commented Sep 22, 2016 at 7:59
-
Hey @BKChedlia regarding event reciver check learningsharepoint.com/2010/06/27/… and seminda.wordpress.com/2011/09/08/…2016-09-22 10:11:41 +00:00Commented Sep 22, 2016 at 10:11