Thursday, January 5, 2012

Use Gridview to Bind list data in SharePoint 2010

Introduction:
Here we will see how we can bind a document library or a list data to a gridview or SPGridView using SharePoint 2010 object model.

Also you can check out some posts on:

- Detecting Memory Leaks in SharePoint 2010

- Cascading dropdownlist in SharePoint 2010 list using jQuery

- Content Search Web Part in SharePoint 2013

Description:
As our requirement here is to bind list or document library data to a SPGridview or a Gridview, I have taken here a Document library and a gridview. We are going to show this in a Visual Web Part. If you want to know the steps to create a Visual Web Part in SharePoint 2010 then you can follw this tutorial.

So in our Visual web part put a gridview control and set the properties and add one column as below:

<asp:GridView ID="grdDocuments" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:HyperLinkField DataTextField="Title" DataNavigateUrlFields="URL" />
</Columns>
</asp:GridView>

And now lets going to the coding side:
Below is the code that will retrieve the data from the document library and Bind the data to the gridview.

void BindDocuments()
        {
            SPWeb mySite = SPContext.Current.Web;
            SPList myList = mySite.Lists["MyDocsLibName"];
            SPListItemCollection items = myList.Items;
            //Here we will make a datatable and we will put our document library data to the data table
            DataTable table;
            table = new DataTable();
            table.Columns.Add("Title", typeof(string));
            table.Columns.Add("URL", typeof(string));

            // Create rows for each splistitem
            DataRow row;
            foreach (SPListItem result in items)
            {
                row = table.Rows.Add();
                row["Title"] = result.Name;
             
                row["URL"] = "Your site url" + result.Url; //here need to append the site url to the item url
            }
            grdDocuments.DataSource = table.DefaultView;
            grdDocuments.DataBind();
        }
The output will come as a list of items with hyperlink and whenever you will click on an item the corresponding image will open.

1 comment: