How to iterate over each row, column and cells in a GridView and get its value

I have a GridView , which is a database binding, on button_click. I want to read a GridView row for each column and read the value of each cell in the row and update the table in the database? I also know how to check if this cell contains null.

I'm trying something like this and stuck:

 protected void SAVE_GRID_Click(object sender, EventArgs e) { int rowscount = GridView2.Rows.Count; int columnscount = GridView2.Columns.Count; for (int i = 0; i < rowscount; i++) { for (int j = 1; j < columnscount; j++) { // I want to get data of each cell in a row // I want to read the corresponding header and store } } } 
+4
source share
3 answers

The easiest way is to use foreach :

 foreach(GridViewRow row in GridView2.Rows) { // here you'll get all rows with RowType=DataRow // others like Header are omitted in a foreach } 

Edit: according to your changes, you are accessing the column incorrectly, you should start at 0:

 foreach(GridViewRow row in GridView2.Rows) { for(int i = 0; i < GridView2.Columns.Count; i++) { String header = GridView2.Columns[i].HeaderText; String cellText = row.Cells[i].Text; } } 
+16
source

As Tim Schmelter said, this is the best way: just change the second loop code in it (GridView2.Columns [i]. Count by row.Cells.Count), so it looks like:

 foreach(GridViewRow row in GridView2.Rows) { for(int i = 0; i < GridView2.Columns.Count; i++) { String header = GridView2.Columns[i].HeaderText; String cellText = row.Cells[i].Text; } } 

thanks.

+5
source
 foreach (DataGridViewRow row in GridView2.Rows) { if ( ! row.IsNewRow) { for (int i = 0; i < GridView2.Columns.Count; i++) { String header = GridView2.Columns[i].HeaderText; String cellText = Convert.ToString(row.Cells[i].Value); } } } 

Here, before iterating for cell values, you need to check NewRow.

0
source

All Articles