Monday, June 1, 2015

Add / Remove Event Receiver from SharePoint List

Introduction

As all we know about event receiver in SharePoint. Let me explain how to add and remove this Event Receiver in the list.

Add Event Receiver


SPList list = web.Lists["List Name"];

var eventReceiverName = list.Title + SPEventReceiverType.ItemAdded;

if (list.EventReceivers.Cast<SPEventReceiverDefinition>().All(x => x.Name != eventReceiverName))
 {
var className = "Class name of Event Receiver";
var assemblyName = "Assembly name of dll";
web.AllowUnsafeUpdates = true;
list.EventReceivers.Add(SPEventReceiverType.ItemAdded, assemblyName, className);
web.AllowUnsafeUpdates = false;
}

Remove Event Receiver

 SPList list = web.Lists["List Name"];
 for (int i = 0; i < list.EventReceivers.Count; i++)
{
               if(list.EventReceivers[i].Type.Equals(SPEventReceiverType.ItemAdded))
               {
                   list.EventReceivers[i].Delete();
               }
}

No comments:

Post a Comment