Tuesday, 22 April 2014

SharePoint 2010: Add an Event Receiver in code

Some requirements demand the adding of Event Receivers in code and not as features. Fortunately, there is a simple method to perform this task.

The following code adds an 'ItemAdding' event receiver in the class 'MyEventReceiver'. The project namespace is 'MyProject'

using (SPSite site = new SPSite("http://blah.com"))
{
   using (SPWeb web = site.OpenWeb())
   {
      SPList list = web.Lists["MyList"];
      list.EventReceivers.Add(SPEventReceiverType.ItemAdding, Assembly.GetExecutingAssembly().FullName, "MyProject.MyEventReceiver");
   }
}




No comments:

Post a Comment