.net 从 DataGridView 中删除行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4950205/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:14:46  来源:igfitidea点击:

Remove row from DataGridView

.netvb.net

提问by Lefteris Gkinis

In order to initialize my VouchersDGV Data Grid View I'm Using the following

为了初始化我的 VouchersDGV 数据网格视图,我使用以下内容

 DGV.AllowUserToDeleteRows = True
 For i = 1 To DGV.RowCount - 1
     DGV.Rows.Remove(DGV.Rows(i - 1))
     DGV.Refresh()
 Next

But when I'm runing it for the first time I take the error of

但是当我第一次运行它时,我会出错

{"Uncommitted new row cannot be deleted."} System.InvalidOperationException

{“无法删除未提交的新行。”} System.InvalidOperationException

If I will continue and run my code and write a new row in my Data Grid and I will try to initialize again (now I have two rows, one has the data and the other is empty) I take this error

如果我将继续并运行我的代码并在我的数据网格中写入一个新行,我将再次尝试初始化(现在我有两行,一个有数据,另一个是空的)我接受这个错误

{"Uncommitted new row cannot be deleted."} System.InvalidOperationException

{“无法删除未提交的新行。”} System.InvalidOperationException

I can't solve it, Please is there someone to assist me on that?

无法解决,请问有大佬帮忙解决吗?

回答by Mohib Sheth

If Not DGV.Rows(i).IsNewRow Then
    DGV.Rows.RemoveAt(i)
End If

Add this condition to your loop. Alternatively, you could also use DGV.RejectChanges() which will reset all the row status to original.

将此条件添加到您的循环中。或者,您也可以使用 DGV.RejectChanges() 将所有行状态重置为原始状态。

回答by Damien

If your goal is to empty the row collection, you can just use the Clear method of the Rows collection:

如果您的目标是清空行集合,则可以使用 Rows 集合的 Clear 方法:

DGV.Rows.Clear()

DGV.Rows.Clear()

Hope this helps.

希望这可以帮助。