0

I've create a foreach loop in C#. I'm trying to loop trough all the rows except for the last one, which is automatically added. Since the cells contains no values I'm getting a NullException.

Important: Setting AllowUsersToAddRows to false is not an option as this function is required.

foreach (DataGridViewRow row in VRFileDataGrid.Rows)
    {
        Console.WriteLine(row.Cells[0].Value.ToString());
    }

I'm not trying to fix met NullReferenceException, I want to know how to perform a loop trough all rows except for the last automatically added row.

Berendschot
  • 3,026
  • 1
  • 21
  • 43

3 Answers3

2

consider using for loop instead of foreach

VRFileDataGrid.Rows.Count - 1 means all rows except the last one

for(int r = 0; r < VRFileDataGrid.Rows.Count - 1; r++)
{
   DataGridViewRow row = VRFileDataGrid.Rows[r];
   Console.WriteLine(row.Cells[0].Value.ToString());
}
ASh
  • 34,632
  • 9
  • 60
  • 82
  • You could also do something with the enumerable, like http://stackoverflow.com/a/1779328/1264905. This would still enable you to use foreach. – molnargab May 24 '15 at 16:27
  • 1
    @molnargab, i think such solution is an overkill here; row count is known, the problem is to exclude the last row. but yes, it also should solve the issue – ASh May 24 '15 at 16:30
1

The auto-added last row will have its IsNewRow property set to true. You can simply skip over it:

foreach (DataGridViewRow row in VRFileDataGrid.Rows)
{
    if (row.IsNewRow)
        continue;

    Console.WriteLine(row.Cells[0].Value.ToString());
}
Ishmaeel
  • 14,138
  • 9
  • 71
  • 83
-2

I fixed it by setting VRFileDataGrid.AllowUserToAddRows = false; before the loop and setting VRFileDataGrid.AllowUserToAddRows = true; after the loop.

Probably not the best solution, but i works fine.

Berendschot
  • 3,026
  • 1
  • 21
  • 43