[英]C# DataGridView throws exception when removing object from BindingList
[英]C# Removing bindinglist item object on datagridview causes Exception
我是C#
新手。
我需要能夠從bindinglist
刪除對象,該列表是datagridview
的數據源。 刪除最后一個項目時,出現以下異常:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Windows.Forms.DataGridViewRow.BuildInheritedRowStyle(Int32 rowIndex,
DataGridViewCellStyle inheritedRowStyle)
at System.Windows.Forms.DataGridViewRow.Paint(Graphics graphics, Rectangle clipBounds,
Rectangle rowBounds, Int32 rowIndex, DataGridViewElementStates rowState, Boolean isFirstDisplayedRow, Boolean isLastVisibleRow)
at System.Windows.Forms.DataGridView.PaintRows(Graphics g, Rectangle boundingRect,
Rectangle clipRect, Boolean singleHorizontalBorderAdded)
at System.Windows.Forms.DataGridView.PaintGrid(Graphics g, Rectangle gridBounds,
Rectangle clipRect, Boolean singleVerticalBorderAdded, Boolean singleHorizontalBorderAdded)
at System.Windows.Forms.DataGridView.OnPaint(PaintEventArgs e)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.DataGridView.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
這是刪除對象的“我的代碼”:
研究是研究對象的綁定表。
private void removeComplete()
{
if (studies.Count == 0)
return;
// Create temp list of copleted studies
List<study> completedStudies = studies.Where(s => s.isComplete() == true).ToList();
if (studies.Count == 0)
{
// do nothing
}
else
{
// If I don't use this line, every row produces the same exception
studies.RaiseListChangedEvents = false;
foreach (study study in completedStudies)
{
try
{
studies.Remove(study);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
break;
}
// Turn it back on after turning it off above
studies.RaiseListChangedEvents = true;
// This is the point where it fails
studies.ResetBindings();
}
}
從我所看到的,datagridview似乎仍在嘗試添加剛剛從源中刪除的行。 這對我來說真的很奇怪。
請幫忙!
感謝對我的原始問題的評論和更多的研究,我發現這是因為removeComplete()方法調用需要在UI線程上。 為此,我使用了BeginInvoke,如下所示:
public delegate void processDelegate();
private void processCompleted(object sender, EventArgs e)
{
processDelegate simpleDelegate = new processDelegate(removeComplete);
BeginInvoke(simpleDelegate);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.