Bind ASP.NET Grid View Using C#

In this article I will explain how to bind ASP.Net GridView control at run time using c#. First a dynamic DataTable with schema(Columns/Structure) is created programmatically using C#/VB.Net and then bind it to GridView in ASP.Net.

Once the Schema is defined, then rows (records) are added to the DataTable.

Once the dynamic DataTable is loaded with records, it is bound to an ASP.Net GridView control.

HTML Markup:
The HTML Markup consists of an ASP.Net GridView with three columns.

<asp:GridView ID="gvUserInfo" HeaderStyle-BackColor="#3AC0F7" HeaderStyle-ForeColor="White"
runat="server" AutoGenerateColumns="false">
  <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="25" />
  <asp:BoundField DataField="UserName" HeaderText="Name" ItemStyle-Width="289" />
  <asp:BoundField DataField="Location" HeaderText="Location" ItemStyle-Width="150" />

Adding data to Data table and bind to GridView:

In the Bind Mentod I am first creating a new instance of DataTable.Then adding three columns to the DataTable Columns collection using the AddRange method of the DataTable.
The AddRange method is a suggested way to replace the traditional way of adding one column at a time using the Add method. In the AddRange method we need to pass an Array of the objects of type DataColumn.
And we need to specify the name and the optional parameter Data Type.
Once the schema is ready i.e., all the columns are created, we can now add rows to the programmatically generated DataTable and bind it to the ASP.Net GridView control.

C# Code Behind:
private void BindGrid()
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
    new DataColumn("UserName", typeof(string)),
    new DataColumn("Location",typeof(string)) });
    dt.Rows.Add(1, "John", "US");
    dt.Rows.Add(2, "Samir", "India");
    dt.Rows.Add(3, "Brad", "France");
    gvUserInfo.DataSource = dt;
  catch (Exception ex)
    //Your Code here

     Hope this Information is useful for you.

Sudheer Gangumolu

I'm a Software Analyst / Developer / Blogger, having good experience in working with different flavors & Customization of SharePoint (i.e.,SP O365 / 2013 / 2010 / 2007) and .Net Apps. Currently, working on SharePoint 2013 / SharePoint O365. Guiding people on my technologies.

    Blogger Comment
    Facebook Comment


Post a Comment