Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
769 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...