I don't understand why this code does not work.
foreach (DataRow dataRow in dataTable.Rows)
{
if (true)
{
dataRow.Delete();
}
}
I don't understand why this code does not work.
foreach (DataRow dataRow in dataTable.Rows)
{
if (true)
{
dataRow.Delete();
}
}
Use this:
Please Refer the snaps to understatnd the working of it.
I Hope this issue resolved now.
You cannot modify a collection while you're iterating on it using a
foreach
statement.you can try something like that :
Where items have a
Count
, this is what I have done:Note, that where objects have a
.GetXXXX()
collection, likeFileInfo
(IIRC), deleting item contents in aforeach
is acceptable. One solution I have considered is creating an extension method that provides a.GetItems()
method.If you call the delete method you just have to call
AcceptChanges()
on the table you are modifying, after the foreach loop.The delete method simply marks the row for deletion.
http://msdn.microsoft.com/en-us/library/system.data.datarow.delete%28v=VS.90%29.aspx
The
Rows
content changes while you are iterating if you delete one row, which renders the iteration invalid.You can, however, copy the rows into a collection first and then iterate over the collection and delete the rows that way. This makes sure that the iteration is not interrupted by changing data to be iterated.