<CharlieDigital/> Programming, Politics, and uhh…pineapples

6Oct/10Off

Programmatically Adding an Event Receiver to a Content Type

You'll recall from a previous post that you can add an event receiver to a content type.

That's all well and good if you're deploying your event receiver with your content type from the get go, but what if you need to associate an event receiver with an existing content type?

// Remove existing definition for the assembly name, class, and type.
foreach(SPEventReceiverDefinition definition in contentType.EventReceivers)
{
	if(definition.Class != className && definition.Assembly != assemblyName
		&& definition.Type != eventReceiverType)
	{
		continue;
	}

	definition.Delete();
	contentType.Update(true);
	break;
}

SPEventReceiverDefinition eventReceiverDefinition = contentType.EventReceivers.Add();
eventReceiverDefinition.Class = className; // String
eventReceiverDefinition.Assembly = assemblyName; // String
eventReceiverDefinition.Type = eventReceiverType; // SPEventReceiverType
eventReceiverDefinition.Data = documentType; // Arbitrary input data (String)
eventReceiverDefinition.Update();

contentType.Update(true);

Easy!

Posted by Charles Chen

Filed under: .Net, SharePoint Comments Off
Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.