Suppose I have 10 lists and add a list event receiver itemadded event to these 10 lists, provided that this event provides the same functionality for all 10 lists. Adding the same event receiver to each list is a headache. If there are more than 10 event receivers in the list, copy the same code n times.
The following provides a method. For Multiple lists, if the event receiver requires the same function, you only need to write the code of one event receiver to add it to multiple lists.
1. In your solution, add a feature and register the event receiver for multiple lists in method featureactivated (). The Code is as follows:
Public override void featureactivated (spfeaturereceiverproperties properties) {spweb oweb = (spweb) properties. feature. parent; speventreceivertype _ eventtype = speventreceivertype. itemadded; oweb. lists [LIST 1]. eventreceivers. add (_ eventtype, assembly. getexecutingassembly (). fullname, "eventreceiverproject1.eventreceiver1. eventreceiver1 "); oweb. lists [List 2]. eventreceivers. add (_ eventtype, assembly. getexecutingassembly (). fullname, "eventreceiverproject1.eventreceiver1. eventreceiver1 "); // Add the remaining 10 lists}
2. Create a content type so that all 10 lists use this content type. Then you can attach the event receiver to this content type.
If you are deploying an event receiver and a content type in the SharePoint solution, ignore this article. However, if you want to associate an event receiver with an existing content type, the following is the sample code:
// Remove the existing Assembly name, class, and type to define foreach (speventreceiverdefinition 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 );