Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through each and every row, column and cells in a GridView and get its value

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
        }
    }       
}
like image 994
Archana B.R Avatar asked Sep 01 '12 12:09

Archana B.R


2 Answers

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;
    }
}
like image 60
Tim Schmelter Avatar answered Nov 19 '22 15:11

Tim Schmelter


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.

like image 22
mkebri Avatar answered Nov 19 '22 15:11

mkebri