"Collection was modified..." Issue

Posted by Tyler Murry on Stack Overflow See other posts from Stack Overflow or by Tyler Murry
Published on 2010-05-25T03:13:00Z Indexed on 2010/05/25 3:21 UTC
Read the original article Hit count: 544

Hey guys,

I've got a function that checks a list of objects to see if they've been clicked and fires the OnClick events accordingly. I believe the function is working correctly, however I'm having an issue:

When I hook onto one of the OnClick events and remove and insert the element into a different position in the list (typical functionality for this program), I get the "Collection was modified..." error.

I believe I understand what is going on:

  • The function cycles through each object firing OnClick events where necessary
  • An event is fired and the object changes places in the list per the hooked function
  • An exception is thrown for modifying the collection while iterating through it

My question is, how to do I allow the function to iterate through all the objects, fire the necessary events at the proper time and still give the user the option of manipulating the object's position in the list?

Thanks, Tyler

© Stack Overflow or respective owner

Related posts about c#

Related posts about best-practices