Creating a Basic Event Handler

The following example shows the basic steps of creating an event handler that 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, but cancelling attempts to delete existing items.

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

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

namespace MyEventHandlers

{
    public class SimpleEventHandler : SPItemEventReceiver    {
    }
}

Windows SharePoint Services 3.0 instantiates an object of your class when actions occur within the list. As a developer, you override the methods of the SharePoint base class for the events you are interested in handling. The methods of the SPItemEventReceiver class that you can override are the following:

The example overrides two methods: ItemDeleting and ItemAdded. Remember that the suffix "ing" indicates that we are handling the event in a synchronous way before the action actually occurs, and the suffix "ed" indicates that we are handling the event in an asynchronous way after the action occurs.

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

You have access to the data associated with the SPListItem object through an object that is provided as an input parameter when your method is called. This object is of type SPItemEventProperties. Through the Cancel property of the SPEventPropertiesBase class you can cancel the event, and through the ErrorMessage property you can display a custom error message on a SharePoint page.

The second method to 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.

C#
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 Registering an Event Handler.

See Also

Tags :


Community Content

Hicham Khabbazy
Not a bug

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

this does not work, since AfterProperties are read only!

Yes it works, besides documentation says it's read only!

Before properties are always empty and we must access via properties.ListItem but After properties work very well!!

ItemAdded example:

public override void ItemAdded(SPItemEventProperties properties)
{

SPListItem listItem = properties.ListItem;
listItem["ows_WorkAddress"] = "Adress";

}

Tags :

MollyBos - MSFT
Removing Event Handlers

Please post questions to forums.msdn.com; there are tons of people who read and respond to questions every day there.

TO UNREGISTER INTEREST in an event, simply use the -= operator instead of the += operator in the event registration pattern.  For example:

  public static class LaserCharger
{
    public static event EventHandler FireMahLazer;
    public static void LaserChargedLol()
    {
        EventHandler foo = FireMahLazer;
        if (foo != null)
            foo(null, EventArgs.Empty);
    }
}
  public class ClassThatConsumesEvent
{
    public void RegisterInterest()
    {
        LaserCharger.FireMahLazer += LaserFired;
    }
    public void UnregisterInterest()
    {
        LaserCharger.FireMahLazer -= LaserFired;
    }
    public void LaserFired(Object sender, EventArgs e)
    {
        System.Console.WriteLine("Laser has fired!");
    }
}

This code describes a simple class that exposes a static event (static so that we don't need an instance of the class in order to fire the event is the only reason; works just as well for instance events) and a method to fire that event.  Notice the event firing method LaserChargedLol()'s pattern--we first create a handle on the event, check that it isn't null, and then invoke it (passing a null and empty event args because they don't matter in this example).  This is because another thread may null the event object after we check it and before we invoke it.  Grabbing a handle on the event object prevents this from happening.  Understanding how .NET implements events is required in order to fully understand this; I would strongly suggest you purchase and read CLR Via C# by J. Richter if you have questions.

Now as for ClassThatConsumesEvent... It has three methods:  A method to register interest, a method to unregister interest, and an event handler.  To register interest, just += the event handler to the event you wish to listen to.  You may often see a different version of this as:

  LaserCharger.FireMahLazer += new EventHandler(LaserFired);
  LaserCharger.FireMahLazer -= new EventHandler(LaserFired);

This is just the longhand version of the code above in RegisterInterest and UnregisterInterest.  They both compile to the same byte code.
Don't forget to unregister interest in events; the event object keeps a reference to all objects that have registered event handlers with it.  If you do not unregister interest, that reference may keep objects alive for a longer time than expected.  In long running applications, this can appear to be a memory leak.

BTW, the Community Content editor SUCKS.

[Response: I'm happy to report that MSDN has significant editor improvements that will be launched later this month.  If you have specific feedback or requests, please post them to our connect feedback site: https://connect.microsoft.com/feedback/default.aspx?SiteID=112.  Thanks!]
Tags :

Page view tracker