Wednesday, April 20, 2011

Add Row / Columns to GridView (Programmatically)


1) Create a DataTable object to which than we will bind the GridView

DataTable dt = new DataTable();
2) IF you need two columns than create two DataColumn objects

DataColumn dc1 = new DataColumn("first", typeof(string));

DataColumn dc2 = new DataColumn("second", typeof(string));
DataColumn dc3 = new DataColumn("third", typeof(string));

Add it to the table

dt.Columns.Add(dc1);

dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
3)Run the loop for as many rows you want to add. eg: 3 rows to be added.

for(int i=0;i<3;i++)// 3 = number of rows needed.

{
   DataRow row1 = dt.NewRow();
   int c = 0;
   while (c < 3)
   {
       row1[c] = "some_data";
       c++;
   }
   dt.Rows.Add(row1 );
}

Now iterate through each datacolumn and create a BoundField foreach column

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;
//Bind the datatable with the GridView.
GridView1.DataBind();
And you have successfully added rows/cols to the grid !

4 comments:

Anonymous said...

Thank you ,its help full.
how can add asp.net control in place of Row in each click if you have idea please help me

Thanks,
Madhu.

Yasser R Shaikh said...

I didnt really understand what you meant by that, but if you want to add an asp.net control dynamically you can use <% %> and a for loop. hope this helps !

Unknown said...

Thanks alot, but I think you do not to add the bound field to the grid view since you already set the data column in the data table.

PRANAB said...

Thanks a lot......

Post a Comment

 

2011 ·Code-Studio by yrus.