Search code examples
c#delete-row

Deleting specific rows from DataTable


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?


Solution

  • 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.