Tuesday 8 May 2012

Create an Event Receiver for a Specific List Instance programmatically

Here we learn how to apply event receiver to list or library programmatically.

1. open vs 2010 

2. New project -> Empty Sharepoint Project 
    Name of your solution project  "AddEventReceiver"



3. Select Farm solution as deployment.And click on Finish.
4. Now add new item Event Receiver Name "DynamicReceiver".


5.Choose List Item Events and custom List with Event you want to add.


 6. After adding event receiver you must remove that from feature so it is not attached to list automatically.



All steps to add receiver is done now just run this code to attach event receiver to list or library.
For that you have to add your dll in gac so simply deploy your project.Now
Go to "run" write assembly in run and click ok. One window open and then find your assembly. In this example find  "AddEventReceiver.dll". Just right click on dll and click on property.
Copy this information.
assembly name and  PublicKeyToken.

Write this code in webpart or appication page to attach event receiver

SPWeb oWeb = SPContext.Current.Web;
string _classname = "AddEventReceiver.DynamicReceiver.DynamicReceiver";
string _assname = "
AddEventReceiver, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4500d411c00104bb";
                oWeb.Lists["ListName"].EventReceivers.Add(SPEventReceiverType.ItemAdded, _assname, _classname);
                oWeb.Lists["
ListName"].EventReceivers.Add(SPEventReceiverType.ItemUpdated, _assname, _classname);
                oWeb.Lists["
ListName"].EventReceivers.Add(SPEventReceiverType.ItemDeleted, _assname, _classname);

No comments:

Post a Comment