繁体   English   中英

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

[英]Remove Last Row Databound DataGridView C#

我正在使用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只包含一行 - 在这种情况下一切正常。

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

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

首先,只需禁用Datagridview的属性即可

dataGridView1.AllowUserToAddRows = false;

然后通过保持-1,只需要使用for循环删除最后一行所需的行数。

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

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

myDataGridView1.AllowUserToAddRows = false

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

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

它起作用了。

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

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

我也有同样的问题。 我找到了解决方案。 尝试将所有行复制到下一行。 然后删除第一行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)

试试吧:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM