In this article I will explain 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.
HTML Markup
The HTML Markup consists of an
ASP.Net GridView with three columns. These columns will be
programmatically added to the dynamically generated DataTable.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespace.
C#
using System.Data;
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.
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#
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, "Rama devi", "India");
dt.Rows.Add(2, "Jason Steve", "America");
dt.Rows.Add(3, "Rajitha Ganesh", "India");
dt.Rows.Add(4, "Kshatriya Dev", "Australia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
ID
|
Name
|
Country
|
1
|
Rama
devi
|
India
|
2
|
Jason
Steve
|
America
|
3
|
Rajitha
Ganesh
|
India
|
4
|
Kshatriya
Dev
|
Australia
|
No comments:
Post a Comment