Saturday, September 6, 2008

Creating a basic Item Event Handler

Scenario:
You want to write an event handler to cancel the deletion of an item from Announcement List ( Type = 104 )

Event Handler Code:


using Microsoft.SharePoint;

namespace TrainingSamples
{
public class DeletingAction : SPItemEventReceiver{
public override void ItemDeleting(SPItemEventProperties properties){
properties.Cancel = true;
properties.ErrorMessage = "Deleting items from " + properties.RelativeWebUrl + " is not supported.";
}
}
}
Feature.xml

<Feature Scope="Web"
Title="Deleting Event Handler"
Id="GUID"
xmlns="http://schemas.microsoft.com/sharepoint/">
<ElementManifests>
<ElementManifest Location="Elements.xml"/>
</ElementManifests>
</Feature>
Elements.xml:

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Receivers ListTemplateId="104">
<Receiver>
<Name>DeletingEventHandler</Name>
<Type>ItemDeleting</Type>
<SequenceNumber>10000</SequenceNumber>
<Assembly>DeletingEventHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a26b5449ac4a4cf3</Assembly>
<Class>DeletingEventHandler.DeletingAction</Class>
<Data></Data>
<Filter></Filter>
</Receiver>
</Receivers>
</Elements>


Additional Notes:
This will attach event handler to any list of Type=104. So If you have specific requirements to attach event handler to a particular list only, then go for a Feature Receiver.

2 comments:

Unknown September 22, 2009 at 2:57 PM  

Two questions...

1. Does this event receiver get applied to existing lists and lists that will be created after the Feature is activated?

2. Will deactivating this feature remove the EventReceivers from the lists automatically?

Thanks

Sandeep September 22, 2009 at 3:03 PM  

As per my understanding , it will not attach events to existing list instances.Also when u deactivate the feature , it does remove the event handlers also