Behseini
Behseini

Reputation: 6330

Unable to access DataGridViewRow cells by index

I am trying to loop through two columns in a DataGridView and add them into a coordinate as below

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

but I am encountring with following error:

Cannot apply indexing with [] to an expression of type 'System.Windows.Forms.DataGridViewRow'

Can you please let me know why this is happening?

Regards,

Upvotes: 2

Views: 3341

Answers (2)

Konrad Morawski
Konrad Morawski

Reputation: 8394

It's fairly simple - DataGridViewRow class does not expose an indexer. You need to access cells via its Cells collection. row.Cells[i] should probably do the trick:

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

Upvotes: 5

Wesley
Wesley

Reputation: 5621

DataGridViewRow is not the collection. You need to run this on the Cells collection :)

Upvotes: 2

Related Questions