C# Bind SQL Server Table in Sharepoint List
-
08-12-2020 - |
Question
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 ?
Solution
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