C# 如何从 DataGridView 中删除行?

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

How to remove rows from DataGridView?

c#.netwinformsdatagridviewbuttonclick

提问by samj28

I have a winform with preloaded DataGridView over it...I want to remove rows from datagridview on selecting or highlighting the rows and clicking over the button...

我有一个带有预加载 DataGridView 的 winform...我想在选择或突出显示行并单击按钮时从 datagridview 中删除行...

Also want to clear all the columns....

还想清除所有列....

Currently i used

目前我使用

foreach (DataGridViewRow dgvr in dataGridView2.Rows)
{
    if (dgvr.Selected == true)
    {
        dataGridView2.Rows.Remove(dgvr);
    }
}

but it is throwing an exception that "rows or not commited" or something....it would be appreciable if any one have any better suggestions....

但它抛出了“行或未提交”或其他内容的异常......如果有人有更好的建议,那将是可观的......

采纳答案by Adam

If you have AllowUserToAddRowsenabled on your DataGridView then you might be accidently deleting the empty row at the bottom of the DataView which is a placeholder for the next user created row. Try disabling this option if not required, otherwise try using code like this:

如果您已AllowUserToAddRows在 DataGridView 上启用,那么您可能会意外删除 DataView 底部的空行,该行是下一个用户创建的行的占位符。如果不需要,请尝试禁用此选项,否则尝试使用如下代码:

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
    if(!row.IsNewRow)
       dataGridView1.Rows.Remove(row);
}