Removing Event Handlers in the Feature Deactivated

Removing Event Handlers in the Feature Deactivated

If you use a featurereciever to install your event handler when you activate or install your feature then you can also uninstall/remove the event handler from the list/lists when the feature is either uninstalled or deactivated.

The code for removing the event handler is slightly more complex than adding the event handler and involves looping through the event receivers on the list and removing the one that matches the assembly name which you pass in.

Code:

[code lang="csharp"]
//Open the parent site and web

using (SPSite site = (SPSite)properties.Feature.Parent)
{
using (SPWeb web = site.OpenWeb())
 {
//Grab the required lists
SPList TheList = web.Lists["Shared Documents"];                
//Declare the full assembly name                   
String AssemblyName = "SharedDocumentsHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=928f76143tc8cbd2";
//Create a new integer
int i;
//Use the above integer to loop through the event recievers on the first list and delete the above assembly
for (i = 0; i < TheList.EventReceivers.Count; i++)
{
if (TheList.EventReceivers[i].Assembly.Equals(AssemblyName))    
{                      
TheList.EventReceivers[i].Delete();
}
//Update the list
TheList.Update();

//Update the SharePoint web                 
web.Update();
}
}
[/code]
You can do the above for the FeatureDeactivating or FeatureUninstalling methods :-).

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">