Hot wo add event receiver to a SharePoint list

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.

  1. private void AddEventReceiverToAList(string siteUrl)  

  2. {  

  3. using (SPSite site = new SPSite(siteUrl))  

  4. {  

  5. using (SPWeb web = site.OpenWeb())
     

  6. {  

  7. try 

  8. {  

  9. SPList list = web.Lists["myList"];  

  10. if (list != null)  

  11. {  

  12. int receivers = list.EventReceivers.Count;
     

  13. string className = "EventReceiverClass";  

  14. string asmName = "EventReceiverAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a865f0ecc234ea51";
     

  15. web.AllowUnsafeUpdates = true;  

  16. bool isAddedReceiverExist = false;  

  17. for (int i = 0; i < receivers; i++)
     

  18. {  

  19. SPEventReceiverDefinition eventReceiver = list.EventReceivers[i];
     

  20. if (eventReceiver.Class == className && eventReceiver.Type == SPEventReceiverType.ItemAdded)
     

  21. {  

  22. isAddedReceiverExist = true;
     

  23. break;
     

  24. }  

  25. }  

  26. if (!isAddedReceiverExist)
     

  27. list.EventReceivers.Add(SPEventReceiverType.ItemAdded, asmName, className);
     

  28. }  

  29. }  

  30. catch { }
     

  31. finally 

  32. {  

  33. web.AllowUnsafeUpdates = false;  

  34. }  

  35. }  

  36. }  

This is very straight forward code and hope you got it.