Ads

Wednesday, 15 May 2013

Remove Event Receiver in Sharepoint List programmatically using feature

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.

No comments:

Post a Comment

Ads