无法通过索引访问DataGridViewRow单元格

时间:2012-08-09 21:44:51

标签: c# datagridview

我正在尝试遍历DataGridView中的两列,并将它们添加到坐标中,如下所示

foreach (DataGridView row in dataGridView1.Rows)
{
    double x = Convert.ToDouble(row["X"]);
    double y = Convert.ToDouble(row["Y"]);
    Coordinate c = new Coordinate(x, y);
    Point p = new Point(c);
    IFeature currentFeature = fs.AddFeature(p);
    for (int i = 0; i < dataGridView1.Columns.Count; i++)
    {
        currentFeature.DataRow[i] = row[i];
    }
}

但我遇到以下错误:

  

无法将带有[]的索引应用于类型的表达式   'System.Windows.Forms.DataGridViewRow'

你能告诉我为什么会这样吗?

此致

2 个答案:

答案 0 :(得分:4)

这很简单 - DataGridViewRow类不会公开索引器。您需要通过其Cells集合访问单元格。 row.Cells[i]应该可以做到这一点:

for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
   currentFeature.DataRow[i] = row.Cells[i].Value as IConvertible;
}

答案 1 :(得分:2)

DataGridViewRow不是该集合。您需要在Cells集合上运行此代码:)