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);
}

4 comments:

  1. hey,
    this is sweet and simple but can u tell where a data table is used or how the data in data table is used

    ReplyDelete
  2. You can use datatable as per your need,
    Either you can loop through the datatable for presnting into a row column manner, or you can use as a datasource for Datagridview.
    Also you can add this table into a dataset, perform queries on that dataset and display the results to some UI.

    ReplyDelete
  3. loudaka ball,na madda first u have to write definition useless fellow

    ReplyDelete
  4. lanzada kodaka etla konjura yodambu doma kuchuka sacchen

    ReplyDelete

SQL - Difference between CAST,CONVERT and PARSE

TODO---