By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,831 Members | 1,031 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,831 IT Pros & Developers. It's quick & easy.

How can I delete a Item in foreach loop

P: n/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();

}
}
----------------------------------------------------------------------------
----------------------------------
Nov 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
You can't.

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

HTH
Alex
"ad" <ad@wfes.tcc.edu.tw> wrote in message
news:Of***************@TK2MSFTNGP15.phx.gbl...
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();

}
}
-------------------------------------------------------------------------- -- ----------------------------------

Nov 19 '05 #2

P: n/a
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.

"ad" <ad@wfes.tcc.edu.tw> wrote in message
news:Of*************@TK2MSFTNGP15.phx.gbl...
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();

}
}
-------------------------------------------------------------------------- -- ----------------------------------

Nov 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.