Yesterday (or earlier this morning) I wrote about a Visual Studio DataGridView error that had me banging my head against a brick wall for a while. This post covers some more of the possible solutions in a little more detail.
I did provide this link to a reference to the solution, but as I found it at the last minute, whilst I was writing the blog itself, I had not had a chance to test out the suggested approaches (I don’t write here often enough to justify throwing away the body of the text I’d written!)
A quick restatement of the problem: After adding a Lookup column to a DataGridView, the form works beautifully until you try to close it, when you get hundreds of the following error: “The following exception occurred in the DataGridView: System.ArgumentException: DataGridViewComboBoxCell value is not valid.”
According to Mark Rideout, who signs himself “DataGridView Program Manager”:
The issue is that the Form’s dispose method is first disposing the datasource that the combobox column is using before it is disposing the DataGridview. This is the same as not databinding the combobox column at all. This only causes a problem when autosizing the rows or autosizing the combobox column since removing the combobox column’s datasource causes the row/column to perform autosize layout. As part of the layout, the combobo cell needs to retrieve the FormattedValue, which raises the DataError since the cell cannot find a match in the combobox (since the combobox column’s datasource is now null).
And the solution as discussed in that post is to put the following code in a FormClosing event on the form:
However, there is a caveat (though not a massive one). If you happen to have set the AutoSizeMode at the individual column level, in code or through the IDE, then the code above will not work. Click the thumbnail to the right to see what it looks like when you set a column size mode in the UI.
In this case, you need to switch off the sizing mode at the column level (again, in the form’s FormClosing event is best):
Note that the form uses DataGridViewAutoSizeColumns mode where at the individual column level you use the ‘singular’ version. I found autocomplete a bit flaky in this area.
Well, I hope that this proves to be of use to someone at some time!