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
Enf IF


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

1 comment: