vb.net 删除 DataGridView C# 中的行

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

Delete row in a DataGridView C#

c#.netvb.netdatagridviewrow

提问by Aan

I tried to loop through my dataGridView1and remove rows which don't satisfy the condition as following:

我试图遍历我的dataGridView1并删除不满足条件的行,如下所示:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (!(Convert.ToDateTime(row.Cells[7].Value) - DateTime.Today).Days <= 0)
    {
        dataGridView1.Rows.Remove(row); //error: Uncommitted new row cannot be deleted.
    }
}

But I got this error:

但我收到了这个错误:

Uncommitted new row cannot be deleted.

无法删除未提交的新行。

I can manage if the code also VB.NET.

如果代码也是 VB.NET,我可以管理。

回答by King King

Don't use foreachin this case, the looped collection may be modified and leads to unpredicted result, sometimes throws exception like collection was modified (encountered mainly in LINQ), use forinstead:

foreach在这种情况下不要使用,循环的集合可能会被修改并导致不可预测的结果,有时会抛出类似集合被修改的异常(主要在 中遇到LINQ),请for改用:

 for(int i = dataGridView1.RowCount-1; i >= 0; i--){
   var row = dataGridView1.Rows[i];
   if (!row.IsNewRow&&!(Convert.ToDateTime(row.Cells[7].Value) - DateTime.Today).Days <= 0){
      dataGridView1.Rows.Remove(row);
   }
 }

Note that we have to loop from the largest index to 0.

请注意,我们必须从最大索引循环到 0。

回答by Edper

Try

尝试

foreach (DataGridViewRow row in dataGridView1.Rows)
{
 if (!(row.Cells.OfType<DataGridViewCell>().All(c=>c.Value == null))
  {
   if (!(Convert.ToDateTime(row.Cells[7].Value) - DateTime.Today).Days <= 0)
   {
     dataGridView1.Rows.Remove(row);
   }
  }
}

回答by C Sharper

try with putting following condition:

尝试放置以下条件:

foreach(DataGridViewRow row in dataGridView1.Rows)
                {

                  if(!row.IsNewRow)
                  {
                     if (!(Convert.ToDateTime(row.Cells[7].Value) - DateTime.Today).Days <= 0)
                     {
                       dataGridView1.Rows.Remove(row);
                     }
                  }

                }