0

我在用户控件上有一个数据网格,其中“修改器”是公开的。我有以下代码:

for (int f = 0; f < gridOperations.Rows.Count; f++)
{
     for (int z = 0; f < gridOperations.Rows[f].Cells.Count; z++)
     {
          MessageBox.Show(gridOperations.Rows[f].Cells[z].Value.ToString());
     }
}

问题是如果 Z 变得高于 0 它给了我

“你调用的对象是空的。”。

我不明白为什么会这样,如果我这样做:

MessageBox.Show(gridOperations.Rows[0].Cells.Count.ToString());

它显示了 9 个项目,所以有单元格,我只是不明白为什么它不允许我访问它们。谢谢!

4

3 回答 3

0

试试下面

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    foreach (DataGridViewCell cell in row.Cells)
    {
        if (cell.Value !=null)
        {
            MessageBox.Show(cell.Value.ToString());
        }
    }
}
于 2013-05-26T14:14:31.267 回答
0

试着这样改变..

for (int f = 0; f < gridOperations.Rows.Count-1; f++)
{
     for (int z = 0; f < gridOperations.ColumnCount -1; z++)
     {
          MessageBox.Show(gridOperations.Rows(f).Cells(z).Value.ToString());
     }
}
于 2013-05-26T14:14:38.563 回答
0

尝试这个;

for (int f = 0; f < gridOperations.Rows.Count; f++)
{
     for (int z = 0; z < gridOperations.Rows[f].Cells.Count; z++)
     {
          MessageBox.Show(gridOperations.Rows[f].Cells[z].Value.ToString());
     }
}

我认为真正的问题在这里,你for用 whihc 限制了你的内部循环,f < gridOperations.Rows[f].Cells.Count我认为应该是z < gridOperations.Rows[f].Cells.Count因为你对该循环的边界应该是当前行的单元格计数,而不是当前行的数量。

作为替代方案,由于DataGridViewRowCollectionDataGridViewCellCollection实现了IEnumerable接口,您可以使用foreach类似循环;

foreach (DataGridViewRow rows in gridOperations.Rows)
{                            
    foreach (DataGridViewCell cells in rows.Cells)
    {
        MessageBox.Show(cells.Value.ToString());
    }
}
于 2013-05-26T14:17:20.623 回答