Safely Removing DataRow In ForEach

Jack Kada picture Jack Kada · Feb 26, 2010 · Viewed 66.8k times · Source

I don't understand why this code does not work.

foreach (DataRow dataRow in dataTable.Rows)
{
    if (true)
    {
        dataRow.Delete();
    }
}

Answer

VMAtm picture VMAtm · Jun 22, 2010

Safest way - use for loop

for (int i = datatable.Rows.Count - 1; i >= 0; i--) 
{
    if (true)
    {
        datatable.Rows[i].Delete();
    }
}

Don't forget to AcceptChanges to remove all marked rows:

datatable.AcceptChanges();