DataGridView的对象数据绑定问题与QUOT;指数-1为不具有值QUOT; [英] DataGridView Object Databinding Issue "Index -1 does not have a value"

查看:175
本文介绍了DataGridView的对象数据绑定问题与QUOT;指数-1为不具有值QUOT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了一组DataGridViews(DGV)的通过属性来显示类的成员。我用的是DGV,以便用户可以右键在视图编辑成员的值(所以我没有显示窗体或编辑该值的文本框)。

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).

我显示类的结构如下:

 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存在,因为字符串的集合不显示为一个字符串DGV。 (长度显示在DGV。

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

的Class2和Class3中有我想在DGV编辑的,所以他们在DGV显示的唯一值。字符串属性

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

当我添加任何类别2或3类各自的父类的新实例,我重新绑定显示集合DGV。

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

添加类的新实例后,它出现在DGV,但如果我去选择值(通过点击在DGV)我得到一个异常,指出指数-1不具有价值

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.

推荐答案

我知道这个问题是旧的,但:

I know this question is old but:

如果您最初绑定一个 集合不会通知变动的DGV(如集合不,而是一个的BindingList一样),初始电流行偏移将被正确设置为 - 1,(因为它是空的。)

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.)

在随后对象添加到您的数据绑定集合,他们仍然会 显示正常发车,但的CurrencyManager不会任何变化通知,而当前行偏移将在-1顽固地保留下来。

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.

所以,当你尝试编辑一行时,CurrencyManager的认为你是在试图抵消-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.

这篇关于DataGridView的对象数据绑定问题与QUOT;指数-1为不具有值QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆