I encountered a frustrating issue using the Windows forms Datagrid today. This problem was also posted without reply on an ms newsgroup. I'm posting my work around here for the record.
Problem DescriptionMy windows form had a tabcontrol, with 2 tab pages, each with a datagrid, bound to a table in a dataset. The problem occurred when the user switched from the second tab to the first, with the last row of the datagrid being left as a new row with default null values. It was in 'edit mode' usually because the user added a new row, or pressed enter, which automatically places the cursor in another empty new row, with the default values. The exception I got was generated by the framework and not from my code, as follows:
Object reference not set to instance of an object, at:
System.Data.DataRowView.CancelEdit() at System.Windows.Forms.CurrencyManager.CancelCurrentEdit() at System.Windows.Forms.DataGrid.OnLeave_Grid() at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
The exception is interesting in that the CurrencyManager kicks in when the focus of the DataGrid has left, and cancels the cell currently being edited.
SolutionI tried several solutions, and eventually worked around the problem by forcing the user to click a button to switch from one tab to the other (I hid the tab change buttons off the screen), and then disabling whichever grid wasn't being used after the button was pressed. This seemed to change the way the DataGrid cancelled the edit of the last row, and the exception doesn't happen now.
It's not an elegant solution, so I'm open to suggestions. I do think the datagrid should be able to execute CancelCurrentEdit without throwing exceptions, and I would be interested to understand why it happens. I guess it will be fixed in .Net version 2.