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");
   }
}




Comments

Popular posts from this blog

SharePoint 2013: Error updating managed account credentials

Error deploying Nintex workflow: An item with the same key has already been added