How can I delete a Item in foreach loop

A

ad

I want to delete a DataRowView in a DataView if the DataRowView not checked
OK.
(CheckRow is a function for checking )
I used the codes below:
But when some row is delete, it fail , the error message is

Collection was modified; enumeration operation may not execute.

How can I do that?

----------------------------------------------------------------------------
----------------------------------

foreach (DataRowView drv in myDataView)
{
if ( !CheckRow(drv) )
{
drv.Delete();

}
}
 
A

AlexS

You can't.

Collect rows to delete inside foreach loop, remove them outside.

HTH
Alex
 
P

Peter Rilling

For things like this, I usually loop backwards and remove the items when
found, for instance

for( int i=drv.Count; i!=0; i-- ){
// remove item here.
}

The reason for going backwards is that it preserves the index position so
you never need to worry about whether you need skip an index or go back one
or something else.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top