【发布时间】: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