Friday, September 25, 2009

Deleting DataRows

This will seem, to many, to be a really elementary, very basic, newbie (or, noobie if you prefer) sort of topic. And it is. But, I still see questions about deleting DataRows asked a great many times on the Forums.

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. This is true whether it's the DefaultView of a DataTable or your own DataView that you’ve created.

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 through the DataView gets around this problem. As does deleting from the DataTable (in either direction) instead of a DataView (although this may not always be the best solution, depending your processing needs).

No comments:

Post a Comment