Bind ASP.NET Grid View Using C#.Net

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

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

Once the dynamic Data Table is loaded with records, it is bound to an ASP.Net Grid View control.

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


<asp:GridView ID="gvUserInfo" HeaderStyle-BackColor="#3AC0F7" HeaderStyle-ForeColor="White"
runat="server" AutoGenerateColumns="false">
  <Columns>
  <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" />
  </Columns>
</asp:GridView>

Adding data to Data table and bind to Grid View:

In the Bind Method I am first creating a new instance of Data Table.Then adding three columns to the Data Table 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 Data Table and bind it to the ASP.Net Grid View control.

C# Code Behind:
private void BindGrid()
 {
  try
  {
    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;
    gvUserInfo.DataBind();
  }
  catch (Exception ex)
  {
    //Your Code here
  }
}

     Hope this Information is useful for you.
Bind ASP.NET Grid View Using C#.Net Bind ASP.NET Grid View Using C#.Net Reviewed by Sudheer Gangumolu on September 13, 2014 Rating: 5

No comments: