Please Check the below complete code to bind SharePoint list items to a DataTable/ Gridview.
In this post, we are 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;
}
For binding 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. We'd like to 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!