删除最后一行数据绑定DataGridView C#

时间:2008-10-07 21:59:55

标签: c# datagridview

我正在使用VS 2008 / C#并将本地的辅助类列表绑定为DataGridView控件的DataSource。在我的助手类列表上调用Remove()方法会触发DataGridView的CellFormatting事件,这是有意义的(有点)。

当删除网格中最后一行的DataBoundItem时(只要网格有多行),DataGridView的Rows集合在此事件触发之前不会更新。因此,在CellFormatting事件处理程序中,我得到一个IndexOutOfRangeException,因为Rows集合太大了。

我尝试使用DataGridView.Rows.Remove()方法删除行,并使用BindingSource进行绑定,而不是直接将List绑定为数据源。

我通过Google找到了一些关于这种情况的引用,但答案要么没有,要么说是在DataGridView或DataGridView.Rows集合上使用Delete()方法 - 目前都不存在。

排序似乎也不是问题,因为执行/不执行排序会产生相同的结果。

“最后一行”唯一的例外是删除问题,如果DataGridView只包含一行 - 在这种情况下一切正常。

6 个答案:

答案 0 :(得分:10)

过去我遇到过这个问题,如果我没记错的话,你可以做两件事之一。从集合中删除记录时,将datagridview上的datasource属性设置为null,然后将其重新绑定到列表中。这应该可以解决问题。

或者,你可以在dataGridview上处理DataError事件,在方法中你可以说e.Cancel = true来抑制异常,或者你可以在那里进一步处理它。

答案 1 :(得分:2)

要隐藏最后一行,请更改datagridview的AllowUserToAddRows属性,如下所示:

myDataGridView1.AllowUserToAddRows = false

答案 2 :(得分:2)

首先,只需将Datagridview的属性设为

即可
dataGridView1.AllowUserToAddRows = false;

然后通过保持-1来删除最后一行所需的行数。

dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);
dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);

答案 3 :(得分:0)

这是一个非常古老的问题,但我通过处理row-remove事件解决了这个问题,如下所示。

private void dgViewItems_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
     dataAdapter.Update((DataTable)bindingSource1.DataSource);
}

并且有效。

答案 4 :(得分:0)

我知道这是一个老问题,但我找到了另一个对我有用的解决方案。在从数据源/绑定源中删除项目之前,取消连接CellFormatting事件的事件处理程序,然后重新连接它。例如:

RemoveHandler DataGridView1.CellFormatting, AddressOf DataGridView1_CellFormatting
Me.BindingSource1.Remove(item)
AddHandler DataGridView1.CellFormatting, AddressOf DataGridView1_CellFormatting

答案 5 :(得分:0)

我有同样的问题。我找到了解决方案。尝试将所有行复制到下一行。然后删除第一行dgv。这个示例代码:

    If Dgv.CurrentCell.RowIndex + 1 = Dgv.Rows.Count Then
        For m = Dgv.Rows.Count - 2 To 0 Step -1
            Dgv.Rows(m + 1).Cells(0).Value = Dgv.Rows(m).Cells(0).Value
            Dgv.Rows(m + 1).Cells(1).Value = Dgv.Rows(m).Cells(1).Value
            Dgv.Rows(m + 1).Cells(2).Value = Dgv.Rows(m).Cells(2).Value
            Dgv.Rows(m + 1).Cells(3).Value = Dgv.Rows(m).Cells(3).Value

        Next
        Dgv.Rows.RemoveAt(0)
        Exit Sub
    End If
    Dgv.Rows.Remove(Dgv.CurrentRow)

尝试一下:)