Friday, December 7, 2012

Creating data table programmatically in C#

Sometimes we need to create the data table programmatically in code behind. Here I am giving you a simple example of creating data table programmatically in C#.


//Create instance of data table
DataTable testTable = new DataTable();

//Add columns to data table
testTable.Columns.Add("ID", typeof(int)); //second a parameter of Add function defines datatype of 
colum
testTable.Columns.Add("Name", typeof(string));
testTable.Columns.Add("City", typeof(string));

//Create a row in data table
DataRow dr = testTable.NewRow();

//Fill all columns with value
dr["ID"] = 1;
dr["Name"] = "Manish";
dr["City"] = "Delhi";

//Add the row into data table
testTable.Rows.Add(dr);


You are done. Now you can bind this data table to data controls like gridview, dropdownlist etc.
Note:- You can create the columns of data table through following way also

DataColumn col1 = new DataColumn("ID", typeof(int));
DataColumn col2 = new DataColumn("Name", typeof(string));
DataColumn col3 = new DataColumn("City", typeof(string));

//Add columns to data table
testTable.Columns.Add(col1);
testTable.Columns.Add(col2);
testTable.Columns.Add(col3);

Happy coding!!

No comments:

Post a Comment

If You Enjoyed This Post Please Take 5 Seconds To Share It.

^ Scroll to Top hgpromo