This is very generic and everyone knows how to add an event receiver. But,
usually we attach the event receiver on a list template, site etc. This post
deals with adding event receiver to a specific list.
- private void AddEventReceiverToAList(string siteUrl)
- {
- using (SPSite site = new SPSite(siteUrl))
- {
- using (SPWeb web = site.OpenWeb())
- {
- try
- {
- SPList list = web.Lists["myList"];
- if (list != null)
- {
- int receivers = list.EventReceivers.Count;
- string className = "EventReceiverClass";
- string asmName = "EventReceiverAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a865f0ecc234ea51";
- web.AllowUnsafeUpdates = true;
- bool isAddedReceiverExist = false;
- for (int i = 0; i < receivers; i++)
- {
- SPEventReceiverDefinition eventReceiver = list.EventReceivers[i];
- if (eventReceiver.Class == className && eventReceiver.Type == SPEventReceiverType.ItemAdded)
- {
- isAddedReceiverExist = true;
- break;
- }
- }
- if (!isAddedReceiverExist)
- list.EventReceivers.Add(SPEventReceiverType.ItemAdded, asmName, className);
- }
- }
- catch { }
- finally
- {
- web.AllowUnsafeUpdates = false;
- }
- }
- }
- }