Introduction
This article explains how to dynamically (programmatically) at runtime create a DataTable using C# and 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.
Dynamically create DataTable and bind to GridView in ASP.Net
In the Page Load event of the page I am first creating a new instance of DataTable. Then I am adding three columns to the DataTable Columns collection using the AddRange method of the DataTable.
The AddRange method is a nice 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.
The AddRange method is a nice 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 i.e. the Type of data the column will hold.
Once the schema is ready i.e. all the columns are defined, we can now add rows to the dynamically generated DataTable and bind it to the ASP.Net GridView control.
C# Code
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, "Vepsh", "United States");
dt.Rows.Add(2, "XYZ", "India");
dt.Rows.Add(3, "ABC", "France");
dt.Rows.Add(4, "PQR", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
{
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, "Vepsh", "United States");
dt.Rows.Add(2, "XYZ", "India");
dt.Rows.Add(3, "ABC", "France");
dt.Rows.Add(4, "PQR", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
No comments:
Post a Comment