How can I delete a Item in foreach loop

  • Thread starter Thread starter ad
  • Start date Start date
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();

}
}
 
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

Back
Top