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.
2. Select the site to which you need to apply this event receiver and chose Deploy as a farm solution option.
3. Add new item and select event receiver from SharePoint items.
4. Chose the list on which you want to apply this event. In this example I have chosen Announcements list and clicked on finish.
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:
- public override void ItemAdding(SPItemEventProperties properties)
- {
- string itemString = string.Format("{0} {1}",
- properties.AfterProperties["Title"].ToString(),
- properties.AfterProperties["Body"].ToString());
-
- if (!CheckValidString(itemString))
- {
- properties.Status = SPEventReceiverStatus.CancelWithError;
- properties.ErrorMessage = "List will not accept 'Error' keyword";
- }
- }
-
- protected bool CheckValidString(string chkString)
- {
- if (chkString.ToLower().Contains("error"))
- {
- return false;
- }
- else
- {
- return true;
- }
- }
6. Rename the feature by selecting feature properties, this will help us to identify our custom property.
7. Deploy the solution and active the site feature.
8. Create an Announcements list and try to add the new item with 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!