SharePoint event receiver example

In this SharePoint tutorial, we will discuss SharePoint event receivers. We will see an event receiver example in SharePoint 2013. In this SharePoint event receiver example, we will see, how to create a unique ID and folder structure automatically using the Event receiver in SharePoint 2013/2016/2019.

What is a SharePoint event receiver?

Event receivers are very important in SharePoint and is availe in all versions of SharePoint like SharePoint 2013, SharePoint 2016 and SharePoint 2019.

We use event receivers to handle various events like:

  • Adding
  • Added
  • Updated
  • Updating
  • Deleting
  • Checking in
  • Checking out, etc.

A simple example of an event receiver, you can send an email to someone when anyone deleted an item from a list. Or you can send an approval email when someone uploads a document to a document library.

There are two types of event receivers are there available in SharePoint:

  • Synchronous Event Receiver (Before Event Receiver): As the name suggest, before events occur before an action occurs. Like you want to check the user permission, before someone trying to delete an item from a SharePoint list.
  • Asynchronous Event Receiver (After Event Receiver): As the name suggests, after events occur after an event occurs like you can send an email to your manager if someone deletes an item from a SharePoint list.

Before creating an event receivers in SharePoint, you should know the base classes that you can use:

  • SPItemEventReceiver
  • SPListEventReceiver
  • SPEmailEventReceiver
  • SPWebEventReceiver
  • SPWorkflowEventReceiver

Now, let us see an event receiver example in SharePoint 2013.

Event receiver example in SharePoint 2013

Let us see how to Create a Unique Project ID and automated folder structure under the document library using Event Receiver in SharePoint.

Below are the steps to create an event receiver in SharePoint 2013/2016/2019 using Visual Studio 2017/2019. Before we start, we have to create two things here.

1: Create a Project master List

event receivers in sharepoint
event receivers in sharepoint

2: Create a Deliverable Library

event receivers in sharepoint 2013
event receivers in sharepoint 2013

Once you created the list, follow the steps to create event receiver in SharePoint 2013/2016/2019.

Step-1:

Open Visual Studio – > Go to solution explorer -> Create a New Item -> Choose Event Receiver -> Click on Add button

event receivers in sharepoint 2013 examples
event receivers in sharepoint 2013 examples

Step-2:

The next page will appear to choose Event Receiver Settings. So here you can select List Item Events and custom list in the event source. Next, you can choose An item was added event as per the below screenshot.

event receivers in sharepoint 2013 for custom list example
event receivers in sharepoint 2013 for custom list example

Step-3:

Next you can follow the below code to use in your visual studio snip to achieve your goal.

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace SharePoint_Webparts.Create_Folder
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class Create_Folder : SPItemEventReceiver
    {
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            string Siteurl = properties.ListItem.Web.Url;
            using (SPSite site = new SPSite(Siteurl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPListItem currentItem = properties.ListItem;
                    currentItem["Project_ID"] = "KM-ID00" + Convert.ToInt32(properties.ListItem["ID"]).ToString();
                    currentItem.Update();
                    SPList spl = web.Lists["Deliverable Library"];
                    var FolderAdded = spl.Items.Add("", SPFileSystemObjectType.Folder, "KM-ID00" + Convert.ToInt32(properties.ListItem["ID"]).ToString());
                    FolderAdded.Update();
                    string[] namesArray = new string[] { "Analysis", "Design", "Development", "Testing", "Deployment" };
                    foreach (string name in namesArray)
                    {
                        SPListItem SubFolder = spl.AddItem(FolderAdded.Folder.ServerRelativeUrl, SPFileSystemObjectType.Folder, name);
                        SubFolder.Update();
                    }
                    web.AllowUnsafeUpdates = false;
                }
            }
        }
    }
}

Step-4:

In Element.xml – you need to modify the Receivers List URl instead of List template ID . You have to update your list URL here.

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers ListUrl="/sites/KMIntranet/Lists/Project%20Master">
      <Receiver>
        <Name>Create_FolderItemAdded</Name>
        <Type>ItemAdded</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>SharePoint_Webparts.Create_Folder.Create_Folder</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>
  </Receivers>
</Elements>

Step-5: Once your code get ready, right click on solution explorer and Deploy the solution.

event receivers in sharepoint 2013 examples
event receivers in sharepoint 2013 examples

Step-6:

Next, go back to your list and add an item to the list and see what happens. Here Project_ID will generate automatically after you save your data. Please look into the below screenshot which is shown in the Project _ID column.

Create a Unique Project ID event receivers in sharepoint
Create a Unique Project ID event receivers in sharepoint

Step-7:

Same time if you will open your SharePoint document library, the folder is created as same name.

automated folder structure under document library using Event Receiver in SharePoint
automated folder structure under document library using Event Receiver in SharePoint

Step-8:

If you open the folder, all folder structure has created automatically here. Please look into the screenshot.

event receivers in sharepoint 2013 examples
event receivers in sharepoint 2013 examples

BeforeProperties and AfterProperties in Event Receiver in SharePoint

Let us discuss on BeforeProperties and AfterProperties in Event Receiver in SharePoint 2013. We will use the BeforeProperties and AfterProperties in Event Receivers in SharePoint 2013/2016/2019.

BeforeProperties and afterProperties are used to get previous values and the current value in the event receiver events in SharePoint. Learn about before properties afterproperties itemupdated in SharePoint 2013.

  • Before properties are used to get previous values in the event receiver events in SharePoint 2013/2016/2019.
  • After properties are used to get current values in the event receiver events in SharePoint 2013/2016/2019.

Recently we got a requirement to get save the previous value before updating in SharePoint 2013. In the case of the ItemUpdating event, it is possible to get the previous value by using the properties.ListItem property and in the AfterProperties, we will be able to get the updated value.

The behavior of BeforeProperties and AfterProperties are different for list and document library in SharePoint 2013.

According to MSDN, For documents, Before and After properties are guaranteed for post events, such as ItemUpdated, but Before properties are not available for post events on SharePoint 2013 list items.

Below is the matrix for both lists and document libraries in SharePoint 2013/2016.

BeforeProperties and AfterProperties for SharePoint List

ListBeforePropertiesAfterPropertiesproperties.ListItem
ItemAddingNo ValueNew ValueNull
ItemAddedNo ValueNew ValueNew Value
ItemUpdatingNo ValueChanged ValueOriginal Value
ItemUpdatedNo ValueChanged ValueChanged Value
ItemDeletingNo ValueNo ValueOriginal Value
ItemDeletedNo ValueNo ValueNull

BeforeProperties and AfterProperties for SharePoint Document Library

LibraryBeforePropertiesAfterPropertiesproperties.ListItem
ItemAddingNo ValueNo ValueNull
ItemAddedNo ValueNo ValueNew Value
ItemUpdatingOriginal ValueChanged ValueOriginal Value
ItemUpdatedOriginal ValueChanged ValueChanged Value
ItemDeletingNo ValueNo ValueOriginal Value
ItemDeletedNo ValueNo ValueNull

For both lists and libraries:

  • No value: Column value is not available
  • New value: This is the column’s new value.
  • Changed value: Updated Column value
  • Original value: This is the Old value, not the updated value.

If you want to compare a column value from the old value with updated value, then you can write like below:

public override void  ItemUpdating(SPItemEventProperties properties)
{
     if (properties.BeforeProperties[“column”] != properties.AfterProperties[“column”])
    {
        properties.Cancel = true;
        properties.ErrorMessage = “This column cannot be changed”;
    }
}

You may like following event receiver tutorials:

In this SharePoint tutorial, we learned what is an event receiver in SharePoint? How to create an event receiver in SharePoint 2013 using visual studio. Here we saw an example of creating folder structure automatically using SharePoint Event receiver.

>