SharePoint 2010 Consume SP List Data to Grid View

There is some data in your SPList and you want to show those list items in a grid view then follow below example. first of all create a visual webpart and put a grid view into that like:

<asp:GridView ID="grdDocuments" runat="server" AutoGenerateColumns="false" >
<Columns>

<asp:BoundField DataField="ID" HeaderText="ID"></asp:BoundField>
<asp:BoundField DataField="Name" HeaderText="Name"></asp:BoundField>
</Columns>
</asp:GridView>


Now we have to do some code for bind data in this grid.

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("ID", typeof(string));
            table.Columns.Add("Name", typeof(string));

            // Create rows for each splistitem
            DataRow row;
            foreach (SPListItem result in items)
            {
                row = table.Rows.Add();
                row["ID"] = result.ID;

                row["Name"] = result.Name;              
            }
            grdDocuments.DataSource = table.DefaultView;
            grdDocuments.DataBind();
        }

Comments

Popular posts from this blog

C# Copy files from one server to another

Suppress StyleCop SA1600

Telerik Rad Grid Sorting