vb.net 删除datagridview中的最后一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21162871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete last row in datagridview
提问by user3080392
I'm trying to delete the last row of a datagridview programmatically, but I'm unable. Here's what I've tried so far:
我试图以编程方式删除 datagridview 的最后一行,但我不能。这是我迄今为止尝试过的:
DataGridView1.Rows.RemoveAt(DataGridView1.Rows.Count - 1)
I've also tried to select last row and then delete it, but that hasn't worked either
我也试过选择最后一行然后删除它,但这也没有用
Me.DataGridView1.Rows(Me.DataGridView1.RowCount - 1).Selected = True
DataGridView1.Rows.Remove(DataGridView1.CurrentRow)
DataGridView1.Rows.Remove(DataGridView1.CurrentRow)
Me.DataGridView1.Rows(Me.DataGridView1.RowCount - 1).Selected = True
For Each row As DataGridViewRow In DataGridView1.SelectedRows DataGridView1.Rows.Remove(row) Next
对于每一行作为 DataGridViewRow In DataGridView1.SelectedRows DataGridView1.Rows.Remove(row) Next
I keep getting an error that says “Uncommitted new row cannot be deleted.” Thanks
我不断收到一条错误消息,提示“无法删除未提交的新行”。谢谢
回答by Ragesh Valeroso
try to set your datagridview with this behavior propertiesAllowUserToAddRowsset it to False
then use this code
尝试使用此行为属性设置您的 datagridviewAllowUserToAddRows将其设置为False
然后使用此代码
DataGridView1.Rows.RemoveAt(DataGridView1.Rows.Count - 1)
回答by Neolisk
Chances are you need to call RejectChanges on your row in the DataSource.
您可能需要在 DataSource 中的行上调用 RejectChanges。
For new rows, it means deletion. Also see this:
对于新行,这意味着删除。另请参阅:
回答by user3080392
Instead of deleting the last row, I ended up just bypassing it. I figured out how to select all of the rows except for the last one, and then I implemented code that referred to just the selected rows.
我没有删除最后一行,而是绕过它。我想出了如何选择除最后一行之外的所有行,然后我实现了仅引用所选行的代码。
Me.DataGridView1.ClearSelection()
Me.DataGridView1.SelectAll()
Me.DataGridView1.Rows(Me.DataGridView1.RowCount - 1).Selected = False
Me.DataGridView1.SelectAll()
Me.DataGridView1.Rows(Me.DataGridView1.RowCount - 1).Selected = False
回答by Tarak Bhavsar
Except deleting the last uncommitted row you can prevent user to select it. By inserting below code to cellclick event of your datagridview.
除了删除最后一个未提交的行,您可以阻止用户选择它。通过将下面的代码插入到 datagridview 的 cellclick 事件中。
Dim i As Integer = DataGridView1.CurrentRow.Index
If DataGridView1.Item(0, i).Value.ToString() = "" Then
MsgBox("Sorry...Blank Row")
DataGridView1.ClearSelection()
DataGridView1.Rows(i - 1).Selected = True
i = i - 1
End If
Your other code goes here.
您的其他代码放在这里。

