In this article I will explain with an example, how to dynamically add Columns (DataColumn) to DataTable at runtime using C# and VB.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#
VB.Net
Dynamically add (insert) Columns (DataColumn) to DataTable at runtime using C# and VB.Nett
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, "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");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn() {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")
GridView1.DataSource = dt
GridView1.DataBind()
End If
Demo
Downloads