为什么DGV在从DataSource中删除项目时会导致未捕获的异常?

时间:2017-04-19 19:34:20

标签: c# winforms exception datagridview bindingsource

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

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

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

导致这种情况的原因是什么?有更好的方法可以防止异常吗?

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

首先:

  

DataGridView中发生以下异常:

     

System.IndexOutOfRangeException:索引413没有值。

     

at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)

     

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

     

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

第二

  

DataGridView中发生以下异常:

     

System.IndexOutOfRangeException:索引413没有值。

     

at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)

     

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

     

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

第三

  

DataGridView中发生以下异常:

     

System.IndexOutOfRangeException:索引413没有值。

     

at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)

     

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

     

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

P.s:只是编写一个快速的DataError事件处理程序,我知道要更多地研究它,但我想我会先从这里开始。

1 个答案:

答案 0 :(得分:1)

查看DGV DataError事件,我可以看到事件args Context属性设置为"显示"对于所有这三个事件。 MSDN记录了显示为

的含义
  

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

因此,我认为这可能与DGV试图在移除过程中更新自身时选择移除的行进行选择。看到我有其他TextBox控件也根据选择显示相同的数据,这看起来像一个可能棘手的循环验证事件堆栈......

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