Deleting specific rows from DataTable

namco picture namco · Apr 13, 2011 · Viewed 387.5k times · Source

I want to delete some rows from DataTable, but it gives an error like this,

Collection was modified; enumeration operation might not execute

I use for deleting this code,

foreach(DataRow dr in dtPerson.Rows){
    if(dr["name"].ToString()=="Joe")
        dr.Delete();
}

So, what is the problem and how to fix it? Which method do you advise?

Answer

Widor picture Widor · Apr 13, 2011

If you delete an item from a collection, that collection has been changed and you can't continue to enumerate through it.

Instead, use a For loop, such as:

for(int i = dtPerson.Rows.Count-1; i >= 0; i--)
{
    DataRow dr = dtPerson.Rows[i];
    if (dr["name"] == "Joe")
        dr.Delete();
}
dtPerson.AcceptChanges();

Note that you are iterating in reverse to avoid skipping a row after deleting the current index.