datagridview动态删除行报错,未将对象引用设置添加到对象的实例。

datagridview 动态删除行报错,未将对象引用设置添加到对象的实例。
未绑定数据库,只动态添加删除,有数据时删除行报错。

 public void DelRow(TelnetSession session)
        {
            try
            {
                
                for (int i = dataGridView1.Rows.Count - 1; i >= 0; i--)
                {
                    DataGridViewRow row = dataGridView1.Rows[i];
                    if (dataGridView1.Rows[i].Cells[7].Value == session.SessionID)
                    {
                        string station = dataGridView1.Rows[i].Cells[0].Value.ToString();
                        this.ShowMsg("设备" + station + "已下线");
                        if(dataGridView1.CurrentRow.Cells[0].Value!=null)
                            dataGridView1.Rows.RemoveAt(i);  //删除一行
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.WriteLog("DelRow函数调用异常", e);
            }
        }

报错:

img

试过的解决方法
①if(!row.IsNewRow)
②if(dataGridView1.Rows.Count>0)
③if(dataGridView1.CurrentRow.Cells[0].Value!=null)

回答不易,求求您采纳点赞哦

您提供的代码存在的问题是,您在当前循环访问 Rows 集合时试图从 DataGridView 中删除一行。这是因为,当您从 DataGridView 中删除一行时,它会影响 Rows 集合的枚举,并导致抛出 InvalidOperationException。

此问题的一种解决方案是创建需要删除的行的单独列表,然后在迭代后从 DataGridView 中删除这些行。这是一个如何做到这一点的例子:

List<DataGridViewRow> rowsToDelete = new List<DataGridViewRow>();
for (int i = dataGridView1.Rows.Count - 1; i >= 0; i--)
{
    DataGridViewRow row = dataGridView1.Rows[i];
    if (dataGridView1.Rows[i].Cells[7].Value == session.SessionID)
    {
        string station = dataGridView1.Rows[i].Cells[0].Value.ToString();
        this.ShowMsg("设备" + station + "已下线");
        if(dataGridView1.CurrentRow.Cells[0].Value!=null)
            rowsToDelete.Add(row);
        return;
    }
}
foreach (DataGridViewRow row in rowsToDelete)
{
    dataGridView1.Rows.Remove(row);
}

此外,我注意到您正在检查 DataGridView 的 currentRow 上的空值,这可能不是您想要的,因为您正在遍历网格上的所有行。相反,您应该检查要从中获取值的单元格上的空值,如下所示:

if(dataGridView1.Rows[i].Cells[0].Value != null) 

这只是可能解决此问题的一种方法,根据项目的具体要求,可能还有其他方法可以达到相同的结果。