Showing posts with label add event receivers to specific list. Show all posts
Showing posts with label add event receivers to specific list. 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.