Adding and removing of SharePoint Event Receiver

Programmatically adding and removing of a custom SharePoint Event Receiver.

Event Receiver class

Sample class definition

public class SequenceFieldItemEventReceiver : SPItemEventReceiver
{
	#region Methods

	public override void ItemAdded(SPItemEventProperties properties)
	{
		// set sequence value in every sequence field
		var sequenceFields = properties.List.Fields.Cast<SPField>().Where(f => f.GetType().Name.Equals("SequenceFieldType"));

		foreach (var sequenceField in sequenceFields.Cast<SequenceFieldType>())
		{
			sequenceField.SetSequenceValue(properties.ListItem);
		}
	}
}

Add

In this example the event receiver class is located in the current executed assembly.

list.EventReceivers.Add(SPEventReceiverType.ItemAdded, Assembly.GetExecutingAssembly().FullName, "YourNamespace.Fields.SequenceFieldItemEventReceiver");
list.Update();

Remove

Removing of the event receiver that has been attached to a list.

var eventReceivers = list.EventReceivers.Cast<SPEventReceiverDefinition>().Where(r => r.Class.Equals("YourNamespace.Fields.SequenceFieldItemEventReceiver")).ToArray();

// there should be only one event receiver, but to get sure we will use the collection
for (int i = 0; i < eventReceivers.Length; i++)
{
	eventReceivers[i].Delete();
}

Leave a Reply

Your email address will not be published. Required fields are marked *

2 + eleven =