【问题标题】:Why does DGV cause uncaught exception when removing item from DataSource?为什么 DGV 从 DataSource 中删除项目时会导致未捕获的异常?
【发布时间】:2017-04-19 19:34:19
【问题描述】:

我有一个带有 DataGridView 的 WinForms 应用程序,它的 DataSource 属性设置为 BindingSource(而 DataSource 又设置为 BindingList)。

一切正常,直到我从 BindingSource 中删除项目以响应用户请求,我为此使用的代码是:

try
{
    // Get the item currently selected by the DGV
    var fc = (FooType)FooBindingSource.Current;
    // Remove the item from the binding source
    FooBindingSource.Remove(fch);
}
catch (Exception fault)
{
    MessageBox.Show(fault.Message);
}

Remove() 导致异常。但是 in 似乎没有直接在此代码的执行行中引发,因为这里的 cathc 没有捕获异常。相反,当我运行应用程序并测试此功能时,我多次看到 DGV 默认错误对话框。但令人惊讶的是,最终结果仍然是该项目确实被正确删除了!

我可以通过在Remove()(使用FooDataGridView.DataSource = null)之前从 DGV 取消绑定 BindingSource 并在之后重新绑定它来解决这个问题。但这感觉... hacky,就像我只是绕过这个问题而不是解决它,因为我不明白是什么导致了这个问题。

我相信在删除项目时正在发生某些事件,例如网格正在被验证或其他什么。

是什么原因造成的,有没有更好的方法来防止异常?

我看到的错误对话框包含以下信息,均标题为“DataGridView 默认错误对话框”

第一:

DataGridView 出现以下异常:

System.IndexOutOfRangeException:索引 413 没有值。

在 System.Windows.Forms.CurrencyManager.get_Item(Int32 索引)

在 System.Windows.Forms.DataGridView.DataGridViewDataConnection.GetError(Int32 rowIndex)

要替换此默认对话框,请处理 DataError 事件。

第二:

DataGridView 出现以下异常:

System.IndexOutOfRangeException:索引 413 没有值。

在 System.Windows.Forms.CurrencyManager.get_Item(Int32 索引)

在 System.Windows.Forms.DataGridView.DataGridViewDataConnection.GetError(Int32 boundColumnIndex, Int32 columnIndex, Int32 rowIndex)

要替换此默认对话框,请处理 DataError 事件。

第三:

DataGridView 出现以下异常:

System.IndexOutOfRangeException:索引 413 没有值。

在 System.Windows.Forms.CurrencyManager.get_Item(Int32 索引)

在 System.Windows.Forms.DataGridView.DataGridViewDataConnection.GetError(Int32 rowIndex)

要替换此默认对话框,请处理 DataError 事件。

P.s:刚刚编写了一个快速的 DataError 事件处理程序,知道要进一步研究这个问题,但我认为我会在这里抢占先机。

【问题讨论】:

  • 你试过 FooBindingSource.RemoveCurrent(); 后跟 FooBindingSource.EndEdit(); 吗?
  • @Steve 恐怕没什么区别

标签: c# winforms exception datagridview bindingsource


【解决方案1】:

查看 DGV DataError 事件,我可以看到所有三个事件的事件 args 上下文属性都设置为“显示”。 MSDN 文档中显示的含义为

显示由数据源填充的单元格时发生数据错误。此值表示单元格无法显示来自数据源的值,或者缺少将数据源中的值转换为单元格的映射。

因此,我认为这可能与 DGV 在删除期间更新自身时试图保持选中的已删除行有关。看到我有其他 TextBox 控件也根据选择显示相同的数据,那么这看起来可能是一种棘手的循环验证事件堆栈......

为了测试这一点,我尝试在删除项目之前立即以编程方式将所选行更改为其他内容 - 这很有效!我可以使用这种方法,但是当用户删除最后一项时,我应该让代码选择哪一行?更多的荆棘和意大利面......所以至少对可能发生的事情有一点了解,我现在可以使用我提到的解除绑定和重新绑定方法。

【讨论】:

    猜你喜欢
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多