Custom List Event Receivers In SharePoint 2013

Event Receiver will help users to interact with the Lists and its items. In the following example I am going to explain how we can create custom list event receivers to display custom error message while adding an item.

Steps to create event receiver:

1. Create an Empty SharePoint project and give project and solution name.

Create an Empty SharePoint project

2. Select the site to which you need to apply this event receiver and chose Deploy as a farm solution option.

chose Deploy as a farm solution option

reference

3. Add new item and select event receiver from SharePoint items.

Event receiver

4. Chose the list on which you want to apply this event. In this example I have chosen Announcements list and clicked on finish.

handle the events

layout

5. Update the following custom code on Item adding event. Here I am checking item properties having any error keyword, if it contains any error keyword, just display an error message "List will not accept 'Error' keyword".

Code:

  1. public override void ItemAdding(SPItemEventProperties properties)  
  2. {  
  3.     string itemString = string.Format("{0} {1}",  
  4.         properties.AfterProperties["Title"].ToString(),  
  5.         properties.AfterProperties["Body"].ToString());  
  6.   
  7.     if (!CheckValidString(itemString))  
  8.     {  
  9.         properties.Status = SPEventReceiverStatus.CancelWithError;  
  10.         properties.ErrorMessage = "List will not accept 'Error' keyword";  
  11.     }  
  12. }  
  13.   
  14. protected bool CheckValidString(string chkString)  
  15. {  
  16.     if (chkString.ToLower().Contains("error"))  
  17.     {  
  18.         return false;  
  19.     }  
  20.     else  
  21.     {  
  22.         return true;  
  23.     }  
  24. }  
6. Rename the feature by selecting feature properties, this will help us to identify our custom property.

selecting feature properties

7. Deploy the solution and active the site feature.

site feature

8. Create an Announcements list and try to add the new item with error keyword.

add the new item

error keyword

9. Now our custom Event Receiver is not allowing to create item with Error keyword.

Hope this article will help you in understanding simple custom list event handlers. Thanks!

 

Up Next
    Ebook Download
    View all
    Learn
    View all