Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView Object Databinding Issue "Index -1 does not have a value"

I am using a set of DataGridViews (dgv) to display a class's members via properties. I use the dgv so that the user can edit the value of the member right in the view (so I dont have to display a form or a textbox for editing that value).

The structure of the class I am displaying is as follows

 Class1 (Displayed in a list view)
     Collection Of class2 (Displayed in a dgv, we'll call it dgv1)
          Collection of class3 (Displayed in a dgv, we'll call it dgv2)

Class3 exists because a collection of strings does not show up as strings in a dgv. (The length is displayed in the dgv.

Class2 and Class3 have string properties that I want editable in the dgv, so they are the only values displayed in the dgv.

When I add a new instance of either class2 or class3 to their respective parent class, I rebind the dgv displaying the collection.

After adding the new instance of the class, it appears in the dgv, but if I go to select the value (by clicking on it in the dgv) I get an exception stating "Index -1 does not have a value"

The issue does not occur if I save the information edited into the form and then reopen the form. The values that I could not previously edit are editable without issue.

like image 661
Dan McClain Avatar asked Dec 18 '22 05:12

Dan McClain


1 Answers

I know this question is old but:

If you initially bind an empty collection that does not inform the DGV of changes (e.g. a Collection does not, but a BindingList does), the initial current row offset will be correctly set to -1, (Because it is empty.)

When you subsequently add objects to your data bound collection they will still display correctly on the grid, but the CurrencyManager will not be informed of any changes, and the current row offset will remain stubbornly at -1.

So, when you try to edit a row, the CurrencyManager thinks you are trying to edit a row at offset -1, and the exception is thrown.

To combat this, you need to rebind before interacting with a row, or initially bind a Collection etc when it contains one or more items.

like image 66
Andy Avatar answered Dec 31 '22 14:12

Andy