The DataTable object represents tabular data as rows, columns and constraints. The DataTable object can be created by instantiating the DataTable class, adding DataColumn objects that define the data and then adding DataRow objects, which are objects that contain the data.
DataTable dt = new DataTable("Emp");
DataColumn eid = new DataColumn("Eid");
eid.DataType = typeof(string);
eid.MaxLength = 10;
eid.Unique = true;
eid.AllowDBNull = false;
eid.Caption = "EID";
dt.Columns.Add(eid);
DataColumn fname = new DataColumn("fname");
fname.DataType = typeof(string);
fname.MaxLength = 35;
fname.AllowDBNull = false;
fname.Caption = "First name";
dt.Columns.Add(fname);
DataColumn lname = new DataColumn("lname");
lname.DataType = typeof(string);
lname.MaxLength = 35;
lname.AllowDBNull = false;
lname.Caption = "last name";
dt.Columns.Add(lname);
DataRow dr = dt.NewRow();
dr["Eid"] = "12345678";
dr["fname"] = "mahak";
dr["lname"] = "garg";
dt.Rows.Add(dr);
// Another way to add the DataRow
dt.Rows.Add("23456", "juhi", "gupta");
The following is the list of DataColumn properties:
DataType: It specifies the datatype of the datacolumn (string,currency…)
MaxLength: -1 means that no maximum length check is performed.
Unique: If it is false, it allows duplicate values.
AllowDBNull: It means that the DataColumn does not need to have a value.
Caption: It is the Column Name property value.
Creating primary key columns: The Primary key consists of one or more columns, which has data that provides a unique identity for each data row. PrimaryKey is the property of the DataTable object.
For example:
dt.PrimaryKey=new dataColumn[] {eid};
Binding the DataTable: A DataTable is bound to any of the databound controls by assigning it to the DataSource property of the databound controls and executing the DataBind method of the control to render the data.
For example:
In this example we take a GridView:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable("Emp");
DataColumn eid = new DataColumn("Eid");
eid.DataType = typeof(string);
eid.MaxLength = 10;
eid.Unique = true;
eid.AllowDBNull = false;
eid.Caption = "EID";
dt.Columns.Add(eid);
DataColumn fname = new DataColumn("fname");
fname.DataType = typeof(string);
fname.MaxLength = 35;
fname.AllowDBNull = false;
fname.Caption = "First name";
dt.Columns.Add(fname);
DataColumn lname = new DataColumn("lname");
lname.DataType = typeof(string);
lname.MaxLength = 35;
lname.AllowDBNull = false;
lname.Caption = "last name";
dt.Columns.Add(lname);
DataRow dr = dt.NewRow();
dr["Eid"] = "12345678";
dr["fname"] = "mahak";
dr["lname"] = "garg";
dt.Rows.Add(dr);
// Another way to add the DataRow
dt.Rows.Add("23456", "juhi", "gupta");
GridView1.DataSource = dt;
GridView1.DataBind();
}