简体   繁体   中英

Delete row in a DataGridView C#

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.

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.

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

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

                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM