Add an event receiver to a specific list programmatically

Creating an event receiver allows you to catch events for specific list types. Such as custom lists, document libraries, announcements, … When we want to catch an event for a specific list, the standard procedure for creating an event receiver changes a bit.

There's an article on MSDN which describes a method by editing the elements.xml file of an event receiver project. However, the same result can be achieved with code.

Basically, an event receiver template will create a feature file which holds a reference to the elements.xml file from the event receiver project. Inside this elements.xml file, the properties of the event receiver are defined, such as the type of list it will be bound to. We want to bypass the elements.xml file and manually attach the event receiver to a specific list's event receivers. The binding itself will be written in a feature event receiver.

Start out with creating a new SharePoint 2010 project and select the Event Receiver template. Fill in any desired properties and click on OK:

new event receiver project

Next, fill in the site where the list is at you want to attach the event receiver. Also choose "farm solution" as the desired trust level.

link farm solution

Click next, choose the event receiver settings. I've chosen for "List Item Events" where "An item was added" should be handled. The event source isn't important, since we'll override the binding:

event receiver settings

When finish is clicked, Visual Studio will create the files based on the template and the chosen settings. A feature will be created with a reference to the EventReceiver1 project. Inside this project an elements.xml file and a code file will be created. The elements.xml file holds the settings of the event receiver. The code file holds the code that will be executed:

event receiver solution explorer

Whenever you want to add more events that have to be captured, click on the EventReceiver1 project and look at the properties window. Here you can enable or disable events that have to be captured. Note that when you disable an already enabled event, the code inside the code file will not be removed. This is a safety built-in for when you accidentally disable an event:

event receiver properties

The next step is removing the connection between the feature and the event receiver project. By doing this we avoid that the elements.xml file is used to bind the event receiver. Double click on the feature file, select the EventReceiver1 project and click on the "<" arrow to remove the project from the feature:

remove event receiver from feature

Save the modification, and right-click the feature file to add a feature event receiver:

add event receiver

If it's not already open, double-click the feature event receiver code file to open it up. Next, uncomment both FeatureActivated and FeatureDeactivating code blocks.

First, declare two constants in your feature class to keep constancy:

1const string _listName = "test";
2const SPEventReceiverType _eventType = SPEventReceiverType.ItemAdded;

Next, write the following code in the FeatureActivated block:

1public override void FeatureActivated(SPFeatureReceiverProperties properties)
2{
3    SPWeb oWeb = (SPWeb)properties.Feature.Parent;
4    oWeb.Lists[_listName].EventReceivers.Add(_eventType, Assembly.GetExecutingAssembly().FullName,"EventReceiverProject1.EventReceiver1.EventReceiver1");
5}

You'll notice that the Assembly namespace isn't recognized so add the following line in your using statements:

1using System.Reflection;

The last parameter of the Add() function can be found in the elements.xml file of the EventReceiver1 project. When you open this file you will see the 2 tags that are also referenced here in our code:

1<Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
2<Class>EventReceiverProject1.EventReceiver1.EventReceiver1</Class>

$SharePoint.Project.AssemblyFullName$ is replaced by Assembly.GetExecutingAssembly().FullName in the code.

The following code will remove the event receiver that was added:

01public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
02{
03    SPWeb oWeb = (SPWeb)properties.Feature.Parent;
04 
05    SPList oList = oWeb.Lists[_listName];
06    for (int i = oList.EventReceivers.Count - 1; i >=0 ; i--)
07    {
08        if (oList.EventReceivers[i].Type.Equals(_eventType))
09        {
10            try
11            {
12                oList.EventReceivers[i].Delete();
13            }
14            catch (Exception e)
15            {
16                // Write to logs
17            }
18        }
19    }
20}