Delete row in a DataGridView C#

2019-08-27 13:40发布

问题:

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

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.

回答1:

Don't use foreach in 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 for instead:

 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.



回答2:

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);
   }
  }
}


回答3:

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);
                     }
                  }

                }