Sunday, June 8, 2008

Adding rows in DataGrid

DataTable dtg = (DataTable) DataGrid1.DataSource;

DataRow dr = dtg.NewRow();

dr["Item_ID"]="ItemID";
dr["Item_Name"]="Item Name";
dr["Item_Desc"]="Item Description";
dr["Item_Amount"]="$15.65";

dtg.Rows.Add(dr);

DataGrid1.DataSource = dtg;

It will work for windows.

If you use DataGrid in ASP then you will have to keep DataTable in Session:

DataTable dtg = new DataTable();

if (Session["SampleDataTable"]==null)
{

DataColumn dc;
dc = new DataColumn("Item_ID",System.Type.GetType("System.String"));
dtg.Columns.Add(dc);
dc = new DataColumn("Item_Name",System.Type.GetType("System.String"));
dtg.Columns.Add(dc);
dc = new DataColumn("Item_Desc",System.Type.GetType("System.String"));
dtg.Columns.Add(dc);
dc = new DataColumn("Item_Amount",System.Type.GetType("System.String"));
dtg.Columns.Add(dc);

}
else {dtg = (DataTable) Session["SampleDataTable"];}

DataRow dr = dtg.NewRow();
dr["Item_ID"]="ItemID";
dr["Item_Name"]="Item Name";
dr["Item_Desc"]="Item Description";
dr["Item_Amount"]="$15.35;
dtg.Rows.Add(dr);

DataGrid1.DataSource=dtg;
DataGrid1.PageSize+=1;
DataGrid1.DataBind();
Session["SampleDataTable"]=dtg;