7

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

我正在尝试这样的事情并陷入困境:

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

4 回答 4

23

最简单的方法是使用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;
    }
}
于 2012-09-01T12:39:12.077 回答
6

正如“Tim Schmelter”所说,这是最好的方法:只需将其代码更改为 seconde 循环( GridView2.Columns[i].Count by row.Cells.Count ),因此看起来似乎是:

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

谢谢你。

于 2014-05-18T15:36:11.313 回答
0
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);
                    }
                }
            }

这里在迭代单元格值之前需要检查 NewRow。

于 2017-07-04T12:48:40.310 回答
0
foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                String header = dataGridView1.Columns[i].HeaderText;
                //String cellText = row.Cells[i].Text;
                DataGridViewColumn column = dataGridView1.Columns[i]; // column[1] selects the required column 
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; // sets the AutoSizeMode of column defined in previous line
                int colWidth = column.Width; // store columns width after auto resize           
                colWidth += 50; // add 30 pixels to what 'colWidth' already is
                this.dataGridView1.Columns[i].Width = colWidth; // set the columns width to the value stored in 'colWidth'
            }
        }
于 2018-07-11T01:30:54.670 回答