Dynamically create DataTable and bind to GridView in ASP.Net - ASP TANMOY

Latest

Friday 28 April 2017

Dynamically create DataTable and bind to GridView in ASP.Net

In this article I will explain how to dynamically (programmatically) at runtime create a DataTable using C# then bind it to GridView in ASP.Net.
First a dynamic DataTable object is created and its schema (Table structure and Columns) is defined programmatically. Once the columns are defined, then rows (records) are added to the dynamically generated DataTable.
Once the dynamic DataTable is populated with records, it is bound to an ASP.Net GridView control.

// Create a DataTable and add two Columns to it
DataTable dt=new DataTable();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Age",typeof(int));

// Create a DataRow, add Name and Age data, and add to the DataTable
DataRow dr=dt.NewRow();
dr["Name"]="Mohammad"; // or dr[0]="Mohammad";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);

// Create another DataRow, add Name and Age data, and add to the DataTable
dr=dt.NewRow();
dr["Name"]="Shahnawaz"; // or dr[0]="Shahnawaz";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);

// DataBind to your UI control, if necessary (a GridView, in this example)
GridView1.DataSource=dt;
GridView1.DataBind();



No comments:

Post a Comment