How to delete row in a DataTable with C# or VB.NET

When you use a DataRow.Delete() method the row is not actually deleted. It is only marked to be deleted after calling DataTable.AcceptChanges(). It is not good idea to remove row with DataTable.Rows.Remove or RemoveAt methods. They forces row removing and causes by iterating the following exception:
'Collection was modified; enumeration operation may not execute'
One more thing to be sure that the iterating will be performed succesfully is to iterate through returned by DataTable.Select() rows (not DataTable.Rows).

For Each row As DataRow In dt.Select()
   If (bool_statement) Then
     row.Delete()
   End If
Next

dt.AcceptChanges

If adapter is used changes can be commited by Update method. All rows with DataRow.RowState of 'Deleted' will be deleted.

2 comments:

  1. thanks you! very useful

    ReplyDelete
  2. Was stuck on this.
    This was very helpful thank you! :)

    Just 1 thing, row.Deleted() should be row.Delete()

    Thanks :)

    ReplyDelete