In this article we can explore the Event Handling features of List through code. Using the SPList in Server Object Model we can access event handling for a list.
We can use the event to perform the following activities:
· Validate the Item
· Log the information
· Create associated items
There are multiple Event Types for a List:
· List Events
· List Item Events (Add, Edit, Delete)
· Web Events
· Feature Events
· Workflow Events
Create Event Receiver Project
For starting with create an Event Receiver project inside Visual Studio.
You will be prompted for the site:
By default the machine site will be shown in the dialog box. Leave the default option of Sandboxed solution and click the Next button.
Select the List Item Events and use event source as Contacts. Check the check boxes for added, updated and deleted events and click the Finish button.
Note: The site url can be changed later. For time being we are using hard coded urls.
On clicking Finish button, the code will be generated for the List Event Receiver and you can place a break point in the ItemAdding event as shown below.
Now execute the application and your Event will be added and activated.
Try adding a new contact inside SharePoint:
On clicking the Save button, the breakpoint inside Visual Studio will get hit:.
You can cancel the operation by using the Cancel property.
You can report an error message using the ErrorMessage property.
Cancel for Delete
You can cancel and item delete by setting the properties.Cancel = true;
public override void ItemDeleting(SPItemEventProperties properties)
properties.ErrorMessage = "Deleting Item is not permitted!";
properties.Cancel = true;
Try deleting an item from the Contacts inside SharePoint:
You will get the following message prompted:
Deploying the Event Receiver
You can take a note that while you stop Visual Studio, the item deletion is allowed inside SharePoint. To make the event receiver permanent, use the project Deploy option.
Now try Deleting an item without Visual Studio Debugging. You will get the same Error Message Dialog and this concludes the Event Creation and Deployment to a SharePoint site.
Properties of Project
You can change the Url and other properties created through the Wizard. Use Project > Properties to access/modify these properties.
The event receiver is actually deployed as a feature inside SharePoint. You can view the Feature properties and the associated xml file under Features special folder as shown below.
The Event code and Elements.xml reside inside the EvntReceiver1 group as shown below.
In this article we have explored the List Event facility of SharePoint. In advanced List Management these flexibilities are great tool for a SharePoint Developer.