Monday, October 5, 2009

Delete rows from DataTable using DataRow

I was surprised by the delete functionality in DataTable.  It was my understanding that when you call DataRow.Delete it marks the row for deletion, but waits for a DataTable.AcceptChanges call before actually removing them, but when I tried to delete inside a For Each dr as DataRow in dt.Rows I was getting an error “Collection was modified”.  Thankfully I ran across a thread that suggested walking backwards through the collection to avoid those types of errors.  I ended up with this to solve my problem:

 

        Do While i >= 0

            If dt.Rows(i)("KEEP_ME"))) = False Then dt.Rows(i).Delete()

            i -= 1

        Loop

        dt.AcceptChanges()

 

 

No comments: