Share via


Binding GridView with SharePoint List

We have developed a custom web part which reads data from SharePoint List ( SharePoint 2010 ) and display in a GridView control by Visual Studio 2010.

In this scenario, we have a list name “Employee” with 4 columns named Name, Sex, Position, Location.

Now, add the following code to the .ascx file:

<asp:GridView ID="grid" runat="server" AutoGenerateColumns="false">  
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Sex" HeaderText="Sex" />
        <asp:BoundField DataField="Position" HeaderText="Position" />   
        <asp:BoundField DataField="Location" HeaderText="Location" />      
    </Columns>
</asp:GridView>

And now, add the following code to the .cs file:


protected void  Page_Load(object  sender, EventArgs e)
{
            SPWeb web = SPContext.Current.Web;
            SPList list = web.Lists["Employee"];
            SPListItemCollection items = list.Items;
            grid.DataSource = items.GetDataTable();
            grid.DataBind();
}