Search This Blog

Monday, November 7, 2011

How to Create DataTable Programmatically in C#, ASP.NET


Most of the times programmers fill the DataTable from database. This action fills the schema of the database table into the DataTable. We can bind data controls like GridView, DropdownList to such DataTable. But somtimes what happens is one needs to create a DataTable programmatically. Here I have put the simple method of creating DataTable programmatically in C#.

Create a DataTable instance

DataTable table = new DataTable();

Create 7 columns for this DataTable
DataColumn col1 = new DataColumn("ID");
DataColumn col2 = new DataColumn("Name");

Define DataType of the Columns
col1.DataType = System.Type.GetType("System.Int");
col2.DataType = System.Type.GetType("System.String");

Add All These Columns into DataTable table

Create a Row in the DataTable table
DataRow row = table.NewRow();

Fill All Columns with Data
row[col1] = 1100;
row[col2] = "Computer Set";

Add the Row into DataTable

Want to bind this DataTable to a GridView?
GridView gvTest=new GridView();
gvTest.DataSource = table;
Post a Comment

Popular Posts