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?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// 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!