I want to delete some rows from DataTable, but it gives an error like this,
Collection was modified; enumeration operation might not execute
I use for deleting this code,
foreach(DataRow dr in dtPerson.Rows){ if(dr["name"].ToString()=="Joe") dr.Delete(); }
So, what is the problem and how to fix it? Which method do you advise?
You need a way to delete the row from DataTable directly without iterating thru the Rows collection. DataTable. Rows collection has Remove method which takes an instance of DataRow as a parameter. So if you can get hold of the DataRow to be deleted, then all you need to do is call usersTable.
To remove the rows in R, use the subsetting in R. There is no built-in function of removing a row from the data frame, but you can access a data frame without some rows specified by the negative index. This process is also called subsetting. This way, you can remove unwanted rows from the data frame.
If you delete an item from a collection, that collection has been changed and you can't continue to enumerate through it.
Instead, use a For loop, such as:
for(int i = dtPerson.Rows.Count-1; i >= 0; i--) { DataRow dr = dtPerson.Rows[i]; if (dr["name"] == "Joe") dr.Delete(); } dtPerson.AcceptChanges();
Note that you are iterating in reverse to avoid skipping a row after deleting the current index.
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