DataTable in C#

Thisa code sample shows how to programmatically create a datatable using C#:


DataTable aTable = new DataTable();
aTable.Columns.Add("ProductID", typeof(int));
aTable.Columns.Add("ProductName", typeof(string));
DataRow dr;
dr = aTable.NewRow();
dr[0] = 12;
dr[1] = "Lap Top";
aTable.Rows.Add(dr);
dr = aTable.NewRow();
dr[0] = 13;
dr[1] = "DeskTop";
aTable.Rows.Add(dr);
dr = aTable.NewRow();
dr[0] = 14;
dr[1] = "Server";
aTable.Rows.Add(dr);
dr = aTable.NewRow();
dr[0] = 15;
dr[1] = "Mac PC";
aTable.Rows.Add(dr);

You can create these rows by getting data from database also

command=new SqlCommand("select * from Product",connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
Dr = aTable.NewRow();
Dr[0] = reader.GetValue(1);
Dr[1] = reader.GetValue(2);
aTable.Rows.Add(Dr);
}


Reference: http://matespoint.blogspot.com/2008/06/creating-datatable-datatable-in-c.html


Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: