1

我有一个 .NET 4.0 WinForms 应用程序。应用程序的表单包含一个网格——一个 System.Windows.Forms.DataGridView 对象

突然间,我得到了一个(不可重现的!)NullReferenceException。调用堆栈如下:

System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Windows.Forms.DataGridView.UnwireEditingControlEvents()
   at System.Windows.Forms.DataGridView.EndEdit(DataGridViewDataErrorContexts context, DataGridViewValidateCellInternal validateCell, Boolean fireCellLeave, Boolean fireCellEnter, Boolean fireRowLeave, Boolean fireRowEnter, Boolean fireLeave, Boolean keepFocus, Boolean resetCurrentCell, Boolean resetAnchorCell)
   at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
   at System.Windows.Forms.DataGridView.set_CurrentCell(DataGridViewCell value)
   at System.Windows.Forms.DataGridView.OnClearingRows()
   at System.Windows.Forms.DataGridViewRowCollection.ClearInternal(Boolean recreateNewRow)
   at System.Windows.Forms.DataGridView.RefreshRows(Boolean scrollIntoView)
   at System.Windows.Forms.DataGridView.DataGridViewDataConnection.ProcessListChanged(ListChangedEventArgs e)
   at System.Windows.Forms.DataGridView.DataGridViewDataConnection.currencyManager_ListChanged(Object sender, ListChangedEventArgs e)
   at System.Windows.Forms.CurrencyManager.OnListChanged(ListChangedEventArgs e)
   at System.Windows.Forms.CurrencyManager.List_ListChanged(Object sender, ListChangedEventArgs e)
   at System.Windows.Forms.BindingSource.OnListChanged(ListChangedEventArgs e)
   at System.Windows.Forms.BindingSource.InnerList_ListChanged(Object sender, ListChangedEventArgs e)
   at System.ComponentModel.BindingList`1.OnListChanged(ListChangedEventArgs e)
   at System.ComponentModel.BindingList`1.FireListChanged(ListChangedType type, Int32 index)
   at System.ComponentModel.BindingList`1.ClearItems()
   at System.Collections.ObjectModel.Collection`1.Clear()
   at <My Code>;

调用 BindingList 派生列表的 Clear 方法。BindingList 派生的列表又在 BindingSource 对象中使用。BindingSource 对象是 DataGridView 的数据源。

我无法理解——为什么会这样?为什么它只是偶尔发生?(到目前为止,我只看到过一次问题)。又该如何避免呢?

4

1 回答 1

0

刚才我自己也遇到了。就我而言,我注意到只有在网格超过 10 行左右并且您立即尝试转到最后一行时才会发生这种情况。我的解决方法是,在设置之后BindingSource,手动将当前单元格设置为第一行中的单元格:

grdConditions.DataSource = myDataSource;
if (grdConditions.Rows.Count > 0)
    grdConditions.CurrentCell = grdConditions[0, grdConditions.RowCount - 1];

似乎为我解决了这个问题。

于 2014-02-21T21:02:15.693 回答