Monday, November 25, 2013

How to remove an event Handler from a list ? A method to detach the event handler

In my previous post i explained about a method to add/attach an event handler to a list.

Now what would you do to remove an event handler from a list ?

The following function would help you to achieve the same in sharepoint..

Just like in the adding event handler post , create the following method.



  private void RemoveHandler(SPList objlist, string strrecieverName)
        {
            try
            {
              
                Guid objGuid = new Guid();
                SPEventReceiverDefinition objEvent = objlist.EventReceivers.Cast<SPEventReceiverDefinition>().FirstOrDefault(l=>string.Compare(l.Name,strrecieverName,true)==0);
                if (objEvent != null)
                {
                    objGuid = objEvent.Id;
                }

                if (objGuid.CompareTo(System.Guid.Empty) != 0)
//Deletes the eventHandler object
                    objEvent.Delete();
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, CommonConstants.ITI_EXCEPTION);
            }
        }
----------------------------------------------------------------------------------------------------------------------------------------------


Now call the RemoveHandler() method from the feature deactivating method of Reciever.cs .

This will remove the adding and deleting event handler from the test list respectively.


   public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb objweb = (SPWeb)properties.Feature.Parent;
            List<SPList> objspLists = new List<SPList>();
            try
            {
                SPList objTestList = objweb.Lists.Cast<SPList>().FirstOrDefault(l => string.Compare(l.Title, "TestList", true) == 0);
       
                if (TestList!= null)
                {
                   //Remove the adding and deleting event handler from the test
                    RemoveHandler(objTestList , "AddingEventHandler");
                    RemoveHandler(objTestList , "DeletingEventHandler");
                  
                }
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, CommonConstants.ITI_EXCEPTION);
            }

        }

-----------------------------------------------------------------------------------------------------------------------------------------------------------------


No comments:

Post a Comment

Rename a Web Application in Sharepoint : A solution using powershell

Here is a small script that will enable you all to change a SharePoint Web Application name . We can use the following SharePoint Pow...