Export (0) Print
Expand All
3 out of 5 rated this helpful - Rate this topic

Example: Creating a List Item Event Handler

Published: May 2010

The following example shows the basic steps used to create an event handler. In this example, the event handler executes code before a list item is deleted or after an item is added. The example works on announcement lists, adding text to the body of new items and cancelling attempts to delete existing items.

You create an event handler assembly in Microsoft Visual Studio by creating a class library. Add a reference to Microsoft.SharePoint.dll and inherit from the Microsoft.SharePoint.SPItemEventReceiver base class, as shown in the following example.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace MyEventHandlers

{
    public class SimpleEventHandler : SPItemEventReceiver    {
    }
}

An object of your class is instantiated when actions occur within the list. As a developer, you override the methods of the base class for the events you are interested in handling. The methods of the SPItemEventReceiver base class that you can override include the following:

The example overrides two methods: ItemDeleting and ItemAdded. Remember that the suffix "-ing" indicates that the event is being handled before the action occurs, and the suffix "-ed" indicates that the event is being handled after the action occurs.

public override void ItemDeleting(SPItemEventProperties properties)
{
    properties.Cancel = true;
    properties.ErrorMessage = "Deleting is not supported.";
}

Data that is associated with the list item is contained in the ListItem property. You can access these property values by using the AfterProperties property bag.

The second method that you must override is ItemAdded. The following example uses the ListItem property to return an object that represents the new list item, and then modifies the body text of the item.

public override void ItemAdded(SPItemEventProperties properties)
{
    SPListItem oItem = properties.ListItem;
    oItem["Body"] = "Body text maintained by the system.";
    oItem.Update();
}

You must register both the ItemDeleting and ItemAdded event receivers, as described in Binding a SharePoint Foundation Event Handler.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.