【问题标题】:A NullReferenceException exception in System.Windows.Forms.DataGridViewSystem.Windows.Forms.DataGridView 中的 NullReferenceException 异常
【发布时间】:2013-04-19 08:55:43
【问题描述】:

我有一个 .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 的数据源。

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

【问题讨论】:

    标签: winforms


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 2017-07-27
      • 2014-07-01
      • 1970-01-01
      • 2010-12-22
      • 2014-08-17
      • 1970-01-01
      相关资源
      最近更新 更多