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


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";
   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.DataSource = dt;
//Bind the datatable with the GridView.
And you have successfully added rows/cols to the grid !


Anonymous said...

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


Yasser R Shaikh said...

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

Chee Su Han 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.