Steps To Create Item Event Receivers In SharePoint 2013 Using C# Server Object Model

Introduction

Item Event Receivers are used to interact with SharePoint items, such as lists or list items. An event receiver responds to the events that occur in any instance of a list definition. In this article, I will explain how to create Item Event Receivers in SharePoint 2013 using C# Server Object Model.

Pre-Requisites

  1. Open Visual Studio.
  2. Open New Project dialog box. Expand Office/SharePoint node and then choose SharePoint Solutions.



  3. Choose the SharePoint 2013 – Empty Project template. Name the project as EventReceiverProject.



  4. Choose "Deploy as a farm solution" option button and choose Finish.



  5. EventReceiverProject SharePoint project got created.

     

Create Item Event Receiver

  1. Right click on EventReceiverProject ->Add -> New Item.



  2. Add Event Receiver from the "Add New Item" window.



  3. In SharePoint Customization Wizard, click on check boxes what are the event receiver want to add on Item like below.

    • An Item is being added- Event receiver will call while item adding in progress.
    • An Item is being updated- Event receiver will call while item update in progress.
    • An Item was added- Event receiver will call when item add completed.
    • An Item was updated- Event receiver will call when item update completed.



  4. Item event receivers are created, as shown in the below image.



  5. Add the custom action to all the event receiver like ItemAdding, ItemUpdating, ItemAdded, ItemUpdated, etc,.
    1. public override void ItemAdding(SPItemEventProperties properties)   
    2. {  
    3.     base.ItemAdding(properties);  
    4.     using(SPWeb web = properties.OpenWeb()) {  
    5.         try {  
    6.             SPListItem currentItem = properties.ListItem;  
    7.             currentItem["UpdatedBy"] = "Event Receiver";  
    8.             currentItem.Update();  
    9.         } catch (Exception ex) {  
    10.             throw ex;  
    11.         }  
    12.     }  
    13. }  


  6. Open Element.xml of the event receiver.



  7. Receiver tag contains ListTemplateId will have the information of which list will receive the custom event to run. I may be generic list template ID or specific list template ID or List URL.



  8. <SequsnceNumber> tag denotes that order in which event should occur.



  9. Add Feature to the SharePoint solution and add this event receiver to that feature.



  10. Build and deploy the SharePoint solution.
  11. Open the SharePoint site, go the list, and add new item to the List which we added in event receiver.



  12. Thus, the Item is added and event receiver updated the items as per our custom action.


Summary

Thus, you have learned how to create Item Event Receivers in SharePoint 2013 using C# Server Object Model.

Up Next
    Ebook Download
    View all
    Learn
    View all