DataGridView 对象数据绑定问题“索引 -1 没有值" [英] DataGridView Object Databinding Issue "Index -1 does not have a value"

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

问题描述

我正在使用一组 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.

当我将 class2 或 class3 的新实例添加到它们各自的父类时,我会重新绑定显示集合的 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 对象数据绑定问题“索引 -1 没有值"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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