Jun 26, 2008

Creating a DataTable | DataTable in C#

Creating a DataTable | DataTable in 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);
}