Showing posts with label event receivers. Show all posts
Showing posts with label event receivers. Show all posts

Wednesday, November 11, 2009

Event Receivers: How to add event receivers to a sharepoint list

Scenario: How to add custom event receivers to a specific sharepoint list using SharePoint Object Model

Approach:

SPList list = web.Lists["MyList"];

string assemblyName = "CustomSharePointEventReceivers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d517db3ed1131947";

string className = "CustomSharePointEventReceivers.MyEventReceivers";
list.EventReceivers.Add(SPEventReceiverType.ItemAdding, assemblyName, className);
list.EventReceivers.Add(SPEventReceiverType.ItemAdded, assemblyName, className);
list.EventReceivers.Add(SPEventReceiverType.ItemUpdating, assemblyName, className);



Note: In general, custom event receivers to a specific list will be added through Sharepoint features by defining a feature event receivers by extending SPFeatureReceiver. In the SPFeatureReceiver, override all the 4 methods i.e, FeatureInstalled,FeatureActivated, FeatureDeactivating and FeatureUninstalling. In these overriden methods, write above code piece.

Event Receivers: Delete all event receivers associated to a list

scenario: How to delete all the event receivers associated to a list?

Approach:


List eventreceivers = new List();

foreach (SPEventReceiverDefinition EventReceiver in list.EventReceivers)
{
eventreceivers.Add(EventReceiver);
}

foreach (SPEventReceiverDefinition er in eventreceivers)
{
er.Delete();
}


Note: We can not have only 2nd foreach loop alone. The current list of event receivers associated to a list gets updated everytime a delete operation is performed. So, an exception will be raised if you use only delete operation.