I don\'t understand why this code does not work.
foreach (DataRow dataRow in dataTable.Rows)
{
if (true)
{
dataRow.Delete();
}
}
<
You cannot modify a collection while you're iterating on it using a foreach
statement.
you can try something like that :
List<DataRow> deletedRows = new List<DataRow>();
foreach (DataRow dataRow in dataTable.Rows)
{
if(true) deletedRows.Add(dataRow);
}
foreach(DataRow dataRow in deletedRows)
{
dataRow.Delete();
}
foreach (DataRow dataRow in dataTable.Rows)
{
if (true)
{
dataRow.Delete();
}
}
dataTable.AcceptChanges();
Please Refer the snaps to understatnd the working of it.
I Hope this issue resolved now.
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.
The easiest way to achieve this by using a List to map rows you want to delete and then delete rows outside DataTable iteration.
C#
List<DataRow> rowsWantToDelete= new List<DataRow>();
foreach (DataRow dr in dt.Rows)
{
if(/*Your condition*/)
{
rowsWantToDelete.Add(dr);
}
}
foreach(DataRow dr in rowsWantToDelete)
{
dt.Rows.Remove(dr);
}
VB
Dim rowsWantToDelete As New List(Of DataRow)
For Each dr As DataRow In dt
If 'Your condition' Then
rowsWantToDelete .Add(dr)
End If
Next
For Each dr As DataRow In rowsWantToDelete
dt.Rows.Remove(dr)
Next
may be my answer not longer useful. exception throw in Foreach with DataRow only appear in .Net 2.0 and earlier, the reason is description at msdn http://msdn.microsoft.com/en-us/library/system.data.datarow.delete(v=vs.80).aspx
If the RowState of the row is Added, the row is removed from the table.
The RowState becomes Deleted after you use the Delete method. It remains Deleted until you call AcceptChanges.
A deleted row can be undeleted by invoking RejectChanges.
to pass this problem you can call DataTable.AcceptChanges() before using foreach
This applies to pretty much any collection. If you try to delete an item while looping through the collection, you will have a problem. For example, if you delete row #3, then the previous row #4 becomes row #3.