Information
Consider a case where you have added an event receiver to SharePoint List on Feature Activation. Now for best SharePoint practices we need to remove the event receiver from SharePoint List on feature deactivation.
I have seen at many places where people have used some weird methods to steps to delete the event receiver from SharePoint list like using PowerShell. To avoid these glitches please find below is the sample code to remove event receiver from SharePoint List.
Assumption
You are writing this code on Site Level Feature Deactivation.
Solution
Place this code in feature deactivation method in Feature Event Receiver.
-
-
-
-
- public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
- {
- try
- {
- if (properties != null)
- {
- SPSite site = properties.Feature.Parent as SPSite;
- var siteID = ((SPSite)properties.Feature.Parent).ID;
-
- using (var spsite = new SPSite(siteID))
- {
- using (var spWeb = spsite.OpenWeb(site.RootWeb.ID))
- {
- SPList oSharePointList = spWeb.Lists.TryGetList("SharePointListName");
-
- if (oSharePointList != null)
- {
- SPEventReceiverDefinitionCollection oSPEventReceiverDefinitionCollection = oSharePointList.EventReceivers;
-
- List<SPEventReceiverDefinition> oRecieversToDelete = new List<SPEventReceiverDefinition>();
-
- foreach (SPEventReceiverDefinition oReciever in oSPEventReceiverDefinitionCollection)
- {
- if (oReciever != null && oReciever.Assembly.Equals(System.Reflection.Assembly.GetExecutingAssembly().FullName))
- {
- oRecieversToDelete.Add(oReciever);
- }
- }
- foreach (SPEventReceiverDefinition oSPEventReceiverDefinition in oRecieversToDelete)
- {
- oSPEventReceiverDefinition.Delete();
- }
- oSharePointList.Update();
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
-
- throw;
- }
- }
Note: You need to replace the List name with the name of the list you are operating on.
Happy SharePointing !!!