I have a GridView
which is databound, on button_click I want to read the GridView
row by row each column and read the value of each cell in a row and update a table in database? I also know how to check if that cell contains null.
I am trying something like this and got 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
}
}
}
The easiest would be using a 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 edits, you are accessing the column incorrectly, you should start with 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;
}
}
As it's said by "Tim Schmelter" this is the best way : just change in it's code the seconde loop ( GridView2.Columns[i].Count by row.Cells.Count ) so it looks seem's that:
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;
}
}
thank you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With