Wednesday, November 18, 2009

Deleting Rows in DataTable - .Net

A colleague asked me about deleting rows from DataTable. He was having an issue when removing the rows of the datatable because he was using method DataTable.Rows.Remove(index).

When you are looping through any collection using for each loop, you cannot modify the collection. In order to Delete the rows, the best way is to use the Delete method of the particular row(s) and once you are done with the loop, method accept changes of DataTable will remove the rows from DataTable. Code example is

' Loop though the table

For Each dr As DataRow In ds.Tables(0).Rows

If (dr("Name") = "ABC" Then

dr.Delete()

End If

Next

ds.Tables(0).AcceptChanges() ' this remains outside of the loop