Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting specific rows from DataTable

Tags:

c#

delete-row

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?

like image 495
namco Avatar asked Apr 13 '11 11:04

namco


People also ask

How to delete selected row from DataTable in c# net?

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.

How do I delete a row in a dataset in R?

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.


1 Answers

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.

like image 93
Widor Avatar answered Oct 24 '22 13:10

Widor