In this article I will explain with an example, how to create DataTable dynamically and bind to GridView in ASP.Net using C# and VB.Net.
HTML Markup
The following HTML Markup consists of:
GridView – For displaying data.
Columns
The GridView consists of three BoundField columns.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Customer Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespace.
C#
VB.Net
Creating DataTable dynamically and binding to GridView in ASP.Net
Inside the Page_Load event handler, an object of DataTable is created.
Then, three columns are added to the DataTable Columns collection using the AddRange method.
An Array of objects of type DataColumn is specified which will hold the name and the optional parameter Data Type i.e. the Type of the column.
Once the schema is ready i.e. all the columns are defined, some rows have been added using the Rows.Add method.
Finally, DataTable is assigned to the DataSource property of the GridView and the GridView is populated.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] {
new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn(2) {
New DataColumn("Id", GetType(Integer)),
New DataColumn("Name", GetType(String)),
New DataColumn("Country", GetType(String))})
dt.Rows.Add(1, "John Hammond", "United States")
dt.Rows.Add(2, "Mudassar Khan", "India")
dt.Rows.Add(3, "Suzanne Mathews", "France")
dt.Rows.Add(4, "Robert Schidner", "Russia")
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End If
End Sub
Screenshot
Demo
Downloads