0

我很陌生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 似乎仍在尝试添加刚刚从源中删除的行。这对我来说真的很奇怪。

请帮忙!

4

1 回答 1

0

感谢对我最初的问题的评论和更多的研究,我发现这是因为 removeComplete() 方法调用需要在 UI 线程上。为此,我使用了 BeginInvoke,如下所示:

public delegate void processDelegate();

private void processCompleted(object sender, EventArgs e)
{

    processDelegate simpleDelegate = new processDelegate(removeComplete);
    BeginInvoke(simpleDelegate);

}
于 2012-09-04T09:06:45.927 回答