Sunday, July 17, 2011

BindingList

A bug was reported in one of my applications. Well, the sequence of actions was not very likely to happen, but still it was a bug. In fact, when a certain action (printing a card) was performed, the program behaved as expected. When the same action was performed a second time, an exception was thrown. Here is what the stack trace said:

System.IndexOutOfRangeException: Index -1 does not have a value.
atSystem.Windows.Forms.CurrencyManager.get_Item(Int32 index)
atSystem.Windows.Forms.CurrencyManager.get_Current()
at System.Windows.Forms.DataGridView.DataGridViewDataConnection.OnRowEnter(DataGridViewCellEventArgs e)
atSystem.Windows.Forms.DataGridView.OnRowEnter(DataGridViewCell&dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred)
at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
at System.Windows.Forms.DataGridView.SetAndSelectCurrentCellAddress(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick, Boolean clearSelection, Boolean forceCurrentCellSelection)
at System.Windows.Forms.DataGridView.MakeFirstDisplayedCellCurrentCell(Boolean includeNewRow)
atSystem.Windows.Forms.DataGridView.OnEnter(EventArgs e)
atSystem.Windows.Forms.Control.NotifyEnter()
atSystem.Windows.Forms.ContainerControl.UpdateFocusedControl()

Well, one thing was obvious - I had nowhere to start from. The exception was not triggered by anything in my code. In fact, when I debugged the application, it happened after a GroupBox status was set to inactive.
There were people on the internet who had this problem before, and generally the suggestion was to look at the places where CurrentCell value of a DataGridView is accessed. Supposedly the problem was that CurrentCell value is null. However, I checked all places where CurrentCell was used and there were no indications of anything wrong happening.

Eventually, I came across a simple and short comment which saved me.

DataGridView - error driving me mad!

"I had the same problem. I changed the list bind to the datasource from a List to a BindingList."

I still don't know what triggered the exception in the first place and don't have much time at the moment to spend on it - as it often happens, if it works, it's good enough already. And the application will be abandoned soon anyway and replaced by a completely new version. So it will remain a mystery for me. by . Also posted on my website