1

I use a foreach loop to get data out of my datagridview using the following code.

foreach (DataGridViewRow row in this.dataGridMultiSubmit.Rows)
{
    Model = row.Cells[0].Value.ToString();
    Module = row.Cells[1].Value.ToString();
    Section = row.Cells[2].Value.ToString();
    FunctionValue = row.Cells[3].Value.ToString();
    NewValue = row.Cells[4].Value.ToString();
    DefaultValue = row.Cells[5].Value.ToString();
    Description = row.Cells[6].Value.ToString();

    MessageBox.Show(Model + Module + Section + FunctionValue + NewValue + DefaultValue + Description);
}

It returns all the rows correctly in the messagebox, but when it run trough all the rows it gives me NullReferenceException was unhandled, how can I fix this?

Alberto
  • 15,626
  • 9
  • 43
  • 56
PandaNL
  • 828
  • 5
  • 18
  • 40

1 Answers1

10

If any one of those Value's are null while you're iterating through all the rows, the call to ToString() will throw an exception.

Try instead:

Model = Convert.ToString(row.Cells[0].Value);

The method Convert.ToString() does an additional check.

  • If the value is null, it returns an empty string.
  • If it's not null, then it performs a ToString().

From your comments, you also want to make sure you don't iterate over the new row that displays at the bottom of the grid. There's a built-in property called IsNewRow.

Gets a value indicating whether the row is the row for new records.

foreach (DataGridViewRow row in this.dataGridMultiSubmit.Rows)
{
    if (row.IsNewRow)
        continue;       // skip row, continue on to the next iteration

    ...
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • This works, however it also shows the empty line in the messagebox (the line in the datagrid where you can add a new line). – PandaNL Feb 13 '14 at 15:34
  • Isn't there a way to always ignore the last line? Otherwise it will always send this extra empty line to my sql database (used a messagebox to make the example simpeler.) – PandaNL Feb 13 '14 at 15:54
  • Yes, they need to be able to add rows, otherwise I could disable adding new rows. – PandaNL Feb 13 '14 at 15:57
  • @PandaNL: You could use a try{}catch{}-block and send the lines to your DB in the try-block. If the action fails (ie, the catch block is executed), nothing would be send to your DB. – waka Feb 13 '14 at 15:58