Monthly Archives: July 2012

Deleteing multiple event receivers error: Collection was modified; enumeration operation may not execute.

 This MSDN article has a nice section on adding and removing event receivers.  However, after trying their code below to delete an event receiver, it will fail if you try to remove multiple event receivers.

you will get this error:

Collection was modified; enumeration operation may not execute.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite sitecollection = properties.Feature.Parent as SPSite;
            SPWeb site = sitecollection.AllWebs[“Docs”];
            SPList list = site.Lists[“MyList”];
            foreach (SPEventReceiverDefinition rd in list.EventReceivers)
            {
                if (rd.Name == “My Event Receiver”)
                    rd.Delete();
            }

To remedy this I specifically get the GUID’s of each event receiver and then delete them declaratively..

  public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

        {

            SPSite sitecollection = properties.Feature.Parent as SPSite;
            SPWeb site = sitecollection.AllWebs[“Site Name”];
            SPList list = site.Lists [“List Name”];

            Guid Event1_Added = Guid.Empty;

            Guid Event1_Updated = Guid.Empty;

            foreach (SPEventReceiverDefinition rd in list.EventReceivers)

            {

                if (rd.Name == “Event1_Added”)

                {

                    Event1_Added [...]

My new friend to show all event receivers on a list

http://spm.codeplex.com/

Download the exe.  It provides a nice interface to drill down and show all the event receivers on a given list.

A few notes on event receivers:

In MOSS 2007, the Item Adding event has a null SPListItem, so use the properties.AfterProperties to get or set the fields before the item is added.  Also, the ItemID is null as the item has not been created yet.

If using Item Added, you can access the list item through properties.ListItem.

Use a Feature Receiver to deploy the event receiver.  This can be a class in the same project that installs on feature activate, and uninstalls on feature deactivate.