Monday, November 23, 2009

Remove Event Receiver in Sharepoint List



In this post I’m going to describe how you can remove an Event Receivers from SharePoint List programmatically. This will be very useful if you have deployed and active custom features, because if you create a custom feature for a custom list, that feature will be added to all the custom lists. Then if you want to create list dynamically and don’t want to add those features you can use this code to remove unwanted events.
public void  removeEvents()
{
 // choose your site
 string strUrl = "http://mysite:5050/";
 using (SPSite site = new SPSite(strUrl))
 {
  using (SPWeb web = site.OpenWeb())
  {
   SPListCollection lists = web.Lists;
   SPList list = web.Lists["My List"];
      
   SPEventReceiverDefinitionCollection erdc = list.EventReceivers;
   List <SPEventReceiverDefinition> eventsToDelete = new List <SPEventReceiverDefinition>();
      
   foreach (SPEventReceiverDefinition erd in erdc)
   {
    if (erd != null)
    {
     try
     {
      eventsToDelete.Add(erd);
     }
     catch (Exception e)
     {
      Console.Write(e.ToString());
     }
    }
   }
   foreach (SPEventReceiverDefinition er in eventsToDelete)
   {
    //if(er.Type == SPEventReceiverType.ItemAdded)
    er.Delete();
   }  
  }
 }
}
Before delete the Event Receiver, if you want you can check the type and delete. In the above code I have commented that part. So if you use the above code as it is, it will remove all the Event Receivers.

2 comments:

  1. awesome, i was struggling how to capture all eventreceivers defnition into a collection, generics is a good way!.....

    ReplyDelete