Most people are used to looping through rows in a DataView using either
for or foreach loops, starting at 0 until the you've finished iterating through all the rows.
This works fine except in the case where you're deleting rows along the way.
In this case, you should use a for loop and iterate backwards through the DataView.
for(int i= MyView.Count-1; i >=0; i--)
{
if (MyView[i]["MyCriteria"].ToString() == "DeleteMe")
{
MyView[i].Delete();
}
else
{
// do some processing here
}
}
So, why does this cause problems if you don't iterate backwards? Because, once a Row is marked as
Deleted, it's gone from the DataView (since, typically, DataViews do not include Deleted rows), and
if you were iterating forward through the DataView, you'd end up skipping past the row immediately after
the one that was just deleted thereby not processing every row in your view. Deleting backwards gets
around this problem.
from a solution provided by Bonnie Berent in Message #1048309 and Message #1048341
|