How to attach an event handler to a specific list in SharePoint?
Ive already read this question how to attach an event receiver to a custom list in sharepoint? but I have a doubt.
When I use the EventReceivers.Add
method to attach my event receiver, does the event receiver feature must be activated, or is it enough to have it installed?
And, if it has to be installed, what ListTemplateId should I use in the elements.xml of the event feature?
Th开发者_如何学Pythonanks in advance
The event receiver is a definition. The definition maps to an assembly and class instance. Using a feature for event receiver association declaratively(specifying listtemplateid) is done when using List Templates. When you are attaching to an specific list based on a list type that is not unique you generally use the object model. By using TemplateTypeID='104', for example, would associate with all lists with that template type.
Using the object model allows you to identify a specific instance so you can simply creates the association. So if you wanted to deploy an event receiver as a feature, you would have a feature that loads the assembly and a feature receiver code that would create the association for you via the object model.
Hopefully this makes sense.
You only need to deploy the solution for your event receiver. This makes the code available to attach to a list.
To attach the event receiver to a specific list use the following code in a console application:
using (SPSite site = new SPSite(url))
{
using (SPWeb siteWeb = site.OpenWeb())
{
SPList list = siteWeb.Lists["TheList"];
SPEventReceiverDefinition defItemAdding = list.EventReceivers.Add();
defItemAdding.Assembly = "MyEventHandlerProject, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=placeTokenHere";
defItemAdding.Class = "MyEventHandlerProject.ClassName";
defItemAdding.Name = "ItemAdding Event";
defItemAdding.Type = SPEventReceiverType.ItemAdding;
defItemAdding.SequenceNumber = 1000;
defItemAdding.Synchronization = SPEventReceiverSynchronization.Synchronous;
defItemAdding.Update();
} }
And you're done!
You can create a console application that will attach an event handler to a Sharepoint list. Check the below link for the code of the sample console application.
http://ceprogrammingnotebook.blogspot.sg/2013/10/attaching-event-handler-to-sharepoint.html
精彩评论