Adding rows and columns to DataGrid Dynamically

Well , it took me sometime to understand how to add rows and columns to the datagrid dynamically using C# and ASP.NET .Infact its very simple provided u remember to few syntax of DataColumn and DataRow.

Here are the steps.

1. Create a DataTable Object which we will use to bind to the datagrid.

DataTable dt=new DataTable();

2. Assume we need two Columns in the DataGrid, so create 2 DataColumn Object.(If u need n columns then we need n DataColumn Objects)

DataColumn col1=new DataColumn("Regno", typeof(System.String));
DataColumn col2=new DataColumn("Name", typeof(System.String));

3. Add it to the table

dt.Columns.Add(col1);
dt.Columns.Add(col2);

4. To add the rows(say 2 rows)

for(int i=0;i<2;i++)
{
DataRow row1 = dt.NewRow();
row1 ["Regno"] = "06PG0225";
row1 ["Name"] ="Senthil Kumar";
dt.Rows.Add(row1 );
}

5. Now iterate through each datacolumn.

foreach (DataColumn col in dt.Columns)
{
BoundField bField = new BoundField
bField.DataField = col.ColumnName;
bField.HeaderText = col.ColumnName;
GridView1.Columns.Add(bField);
}
GridView1.DataSource = dt;
GridView1.DataBind();

6. Now run the Page and Check your GridView1 filled with records…

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

No Responses

  1. Adding rows and columns to DataGrid Dynamically | ProgramInDotnet August 7, 2011 Reply

Leave a Reply


x

Interesting BlogPosts to read

3 Years @ Trivium eSolutions
Looked like it was only few months back that i graduated from my college , but the time is running s...
How to bind Data to ListBox in Windows Phone ?
The below code demonstrates a really simple way of binding data to the Standard ListBox in Windows P...
Application Compatibility Series on Windows 7

Well , it took me sometime to understand how to add rows and columns to the datagrid dynamically.Infact its very simple provided u remember to few syntax of DataColumn and DataRow.

Here are the steps.