0

I have a DataGridView, whose DataSource is a DataTable. The user is allowed to modify the values in one specific cell in each row. I am interested in getting an IEnumerable of objects represented by rows that have been modified by the user.

The form implements a property as follows:

public IEnumerable<Invoice> modifiedInvoiceRecords
{
    get
    {
        DataRowCollection modifiedRows = ((DataTable)dataGridView_invoiceHistory.DataSource).GetChanges(DataRowState.Modified).Rows;
         // iterate through the modified rows and yield return objects
    }
}

This yields a

NullReferenceException

Debugging shows that the modifiedRows variable is always null. Why is this so?

Al2110
  • 566
  • 9
  • 25
  • 1
    Generally you want to avoid writing statements like `((DataTable)dataGridView_invoiceHistory.DataSource).GetChanges(DataRowState.Modified).Rows`. Whilst doing so requires less code you increase the risk of runtime issues due to lack of error checking in the code. 1) DataSource could be `null` 2) `GetChanges` **can** return `null` 3) Calling `Rows` on a possibly `null` object –  Oct 18 '20 at 10:38
  • 2
    You probably forgot to call `AcceptChanges()` right after the DataTable was loaded, so all Rows have the `Added` status. Call `AcceptChanges()` after you have filled the DataTable and `[DataGridView].EndEdit()` before reading the new status of those rows. Add an Elvis at the end: `.GetChanges(DataRowState.Modified)?.Rows;` (if you're sure that the DataTable is not null at that point). As mentioned, you should break that *fancy line* of code into its parts. – Jimi Oct 18 '20 at 11:16

0 Answers0