When I tried to delete event receivers from my content type by deactivating a feature I kept getting the following error:

Collection was modified; enumeration operation may not execute.

My code looked something like this:

foreach( SPEventReceiverDefinition er in contentType.EventReceivers)

{

if( er.Class == “MyNameSpace.MyEventHandlerClass”)

{

er.Delete();

}

}

The first event handler was deleted without any problems however this would then update the contentType.EventReceivers and therefore the code would fail.

The easiest solution I found for this problem is to reload the list of event receivers after every deletion

 

bool removedHandler = true;

while(removedHandler == true)

{

removedHandler =false;

foreach(SPEventReceiverDefinition er in contentType.EventReceivers)

{

if(er.Class == “MyNameSpace.MyEventHandlerClass”)

{

er.Delete();

removedHandler =true;

break;

}

}

}

Advertisements