我有一个数据绑定(bind)的GridView,在button_click上我想逐行逐行读取GridView,并读取一行中每个单元格的值并更新数据库中的表?我也知道如何检查该单元格是否包含null。

我正在尝试类似的事情并被卡住:

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
        }
    }
}

最佳答案

最简单的方法是使用foreach:

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

编辑:根据您的编辑,您正在错误地访问该列,您应该以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;
    }
}

10-07 16:11