Here in this example in my sharepoint site i have created a list called "Employee Details"
with two columns "Name" and "EmpID".
Now in my sharepoint visual webpart project ,i have placed a datagrid and renamed it to "grdDisplay".
Then i used the following in the code behind page to fetch data from the list into the datagrid.
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.IO;
namespace fetchlistdata
{
public partial class fetchlistdataUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
gridData();
}
protected void gridData()
{
SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
SPList list = web.Lists["Employee Details"];
SPQuery query = new SPQuery();
SPListItemCollection items = list.GetItems(query);
DataTable tbl = new DataTable();
tbl.Columns.Add("Name");
tbl.Columns.Add("EmpID");
DataRow tr;
foreach (SPListItem item in items)
{
tr = tbl.Rows.Add();
tr["Name"] = Convert.ToString(item["Name]);
tr["EmpID"] = Convert.ToString(item["EmpID"]);
}
grdDisplay.DataSource = tbl;
grdDisplay.DataBind();
}
}
}