Wednesday, December 28, 2011

Bind data from a SharePoint list to DataTable

The following is the complete code to bind SharePoint list items to a DataTable.
In this post, I keep using the list named "Employee" with 5 column: Title, Birthday, Male, Position, Salary.
At first, we need to create an empty DataTable with its column

       protected DataTable dataTableInitiate()
      {
            DataTable dt = new DataTable();
            DataColumn col = dt.Columns.Add("ID", typeof(string));
            col.AutoIncrement = true;
            col.AutoIncrementStep = 1;
            col.AutoIncrementSeed = 1;
            dt.Columns.Add("Title", typeof(string));
            dt.Columns.Add("Birthday", typeof(string));
            dt.Columns.Add("Male", typeof(string));
            dt.Columns.Add("Position", typeof(string));
            dt.Columns.Add("Salary", typeof(string));                    
            return dt;
      }

Then, bind the item from the SharePoint list to the DataTable that we have just created:
      protected DataTable bindToDataTable(SPListItemCollection itemCol)
      {
            DataTable dt = dataTableInitiate();
            if (itemCol.Count > 0)
            {
                foreach (SPListItem item in itemCol)
                {
                    DataRow dr = dt.NewRow();
                    dr["ID"] = int.Parse(item["ID"].ToString());
                    dr["Title"] = item["Title"] != null ? item["Title"].ToString() : string.Empty;
                    dr["Birthday"] = item["Birthday"] != null ? item["Birthday"].ToString() : string.Empty;
                    dr["Male"] = item["Male"].ToString() == "True" ? "Yes" : "No";
                    dr["Position"] = item["Position"] != null ? item["Position"].ToString() : string.Empty;
                    dr["Salary"] = item["Salary"] != null ? item["Salary"].ToString() : string.Empty;                   
                    dt.Rows.Add(dr);
                }
            }
            return dt;
       }

We've completed copying data from SharePoint list items to DataTable. I'd like bind data from this DataTable to the GridView control.

         protected void bindToGrid()
        {
            SPWeb web = SPContext.Current.Web;
            SPList list = web.Lists["Employee"];
            SPListItemCollection items = list.Items;
            DataTable dt = new DataTable();
            dt = bindToDataTable(items);
            grid.DataSource = dt;
            grid.DataBind();
        }

Hope this helps! :)

Read more:

Read and display Sharepoint list data in GridView control

2 comments:

skofi said...
This comment has been removed by the author.
Anonymous said...

populate gridview with data from datatable

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews