我有一个.NET 4.0 WinForms应用程序。应用程序的表单包含一个Grid - 一个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派生列表。反过来,BindingList派生列表在BindingSource对象中使用。 BindingSource对象是DataGridView的数据源。
我无法理解 - 为什么会这样?为什么它有时会发生? (到目前为止,我只看过一次这个问题)。 如何避免这种情况?
答案 0 :(得分:0)
刚才进入这个问题。在我的情况下,我注意到只有当网格超过大约10行左右时才会发生这种情况,并且您会立即尝试转到最后一行。在设置BindingSource
之后,我的解决方法是手动将当前单元格设置为第一行中的单元格:
grdConditions.DataSource = myDataSource;
if (grdConditions.Rows.Count > 0)
grdConditions.CurrentCell = grdConditions[0, grdConditions.RowCount - 1];
似乎为我解决了这个问题。