Sunday, January 16, 2011

In my previous post, we saw how we added an event receiver to a list. Now, we will see how to delete the existing event receiver on a list.
private void DeleteEventReceiverFromAList(string siteUrl)
    {
        using (SPSite site = new SPSite(siteUrl))
        {
            using(SPWeb web = site.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["myList"];
                    if (list != null)
                    {
                        string className = "EventReceiverClass";
                        string asmName = "EventReceiverAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a865f0ecc234ea51";
                        web.AllowUnsafeUpdates = true;

                        int receivers = list.EventReceivers.Count;
                        bool isAddedReceiverExist = false;
                        bool isUpdatedReceiverExist = false;
                        for (int i = 0; i < receivers; i++)
                        {
                            SPEventReceiverDefinition eventReceiver = list.EventReceivers[i];
                            if (eventReceiver.Class == className && eventReceiver.Type == SPEventReceiverType.ItemAdded)
                            {
                                eventReceiver.Delete();
                                break;
                            }
                        }
                    }
                }
                catch { }
                finally
                {
                    web.AllowUnsafeUpdates = false;
                }
            }
        }
    }
In this code also, there is nothing to explain very detail. Please let me know if you have any questions.

3 comments:

  1. Praveen

    RootWeb shud not be disposed.

    ReplyDelete
  2. Thanks. Sorry for that stupid mistake.

    ReplyDelete
  3. Is there any purpose for the below statement?

    string asmName = "EventReceiverAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a865f0ecc234ea51";

    ReplyDelete