Sunday, September 25, 2011

Delete rows in DataTable using "foreach"

If you try to delete multiple rows in a DataTable with certain conditions using the foreach loop, you may get the following error:
"Collection was modified; enumeration operation might not execute."
For such cases, use the following method:
DataRow[] deleteRows = myDataTable.Select("mycondition = true");

foreach (DataRow deleteRow in deleteRows)
{
    deleteRow.Delete();
    deleteFound = true;
}

If you find this post helpful, would you buy me a coffee?


No comments:

Post a Comment