I don't understand why this code does not work.
foreach (DataRow dataRow in dataTable.Rows) { if (true) { dataRow.Delete(); } }
There are two methods you can use to delete a DataRow object from a DataTable object: the Remove method of the DataRowCollection object, and the Delete method of the DataRow object. Whereas the Remove method deletes a DataRow from the DataRowCollection, the Delete method only marks the row for deletion.
Safest way - use for
loop
for (int i = datatable.Rows.Count - 1; i >= 0; i--) { if (true) { datatable.Rows[i].Delete(); } }
Don't forget to AcceptChanges
to remove all marked rows:
datatable.AcceptChanges();
Even though DataRow.Delete
doesn't modify the state of the collection, Microsoft documentation states that you shouldn't call it while iterating over the collection:
Neither Delete nor Remove should be called in a foreach loop while iterating through a DataRowCollection object. Delete nor Remove modify the state of the collection.
The best solution is usually to create a separate collection (e.g. a List<DataRow>
) of items you want to remove, and then remove them after you've finished iterating.
This is also the solution for situations where you want to remove items from a collection, as most collections in .NET don't allow you to change the contents of the collection while you're iterating over it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With