Normally deleting from a collection while enumerating will throw an exception:
Collection was modified; enumeration operation might not execute.
In this case, if the data rows haven't just been added, calling DataRow.Delete()
doesn't remove the row; it sets the RowState
to Deleted
, but the row remains in the collection until you call AcceptChanges
(see the documentation for DataRow.Delete()
).
So the row is still in the DataTable
and the second time you enumerate the collection, the code tries to access the field value and you get the exception:
DeletedRowInaccessibleException: Deleted row information cannot be accessed through the row.
To avoid this error, you can either call AcceptChanges
to commit the deletion or check the RowState
as mentioned in the answer linked to by @Grant Winney.
To see an example of this, you can run this code:
var table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Rows.Add("foo");
table.Rows.Add("bar");
table.AcceptChanges();
foreach(DataRow row in table.Rows)
{
if ((string)row["Name"] == "foo")
{
row.Delete();
}
}
Console.WriteLine(table.Rows[0].RowState); // Deleted
Console.WriteLine(table.Rows.Count); // 2
table.Rows[0].AcceptChanges();
Console.WriteLine(table.Rows.Count); // 1