How can I delete a Item in foreach loop

Discussion in 'ASP .Net' started by ad, Jun 5, 2005.

  1. ad

    ad Guest

    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();

    }
    }
     
    ad, Jun 5, 2005
    #1
    1. Advertisements

  2. ad

    AlexS Guest

    You can't.

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

    HTH
    Alex
     
    AlexS, Jun 5, 2005
    #2
    1. Advertisements

  3. 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.
     
    Peter Rilling, Jun 6, 2005
    #3
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.