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 
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

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

Happy coding!!

No comments:

Post a Comment

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

^ Scroll to Top hgpromo