Friday, December 2, 2011

Read and display Sharepoint list data in GridView control

I have developed a custom web part which reads data from SharePoint List and display in a GridView control by Visual Studio 2010.
In this scenario, I have a list name "Employee" with 4 collumns named Title, Birthday, Male, Position.

Add the following code to the .ascx file


<asp:GridView ID="grid" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Title" HeaderText="Title" />
        <asp:BoundField DataField="Birthday" HeaderText="Birthday" />
        <asp:BoundField DataField="Male" HeaderText="Male" />  
        <asp:BoundField DataField="Position" HeaderText="Position" />     
    </Columns>
</asp:GridView>

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();
}

Add the web part to the Sharepoint page, we have the following result



Hope this helps!

Read more:

Bind data from a SharePoint list to DataTable

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

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