Add EventReceiver to specific List


public class ListEventReceiverController
{
    const string EVENT_RV_NAME = "CancelPublishMajor";
    public static void AddItemEventReceiver(SPList list, string strEventReceiverClassName, SPEventReceiverType eventReceiverType)
    {
        if (list != null)
        {
            bool found = false;
            foreach (SPEventReceiverDefinition eventreceiver in list.EventReceivers)
            {
                if (eventreceiver.Class == strEventReceiverClassName)
                {
                    found = true;
                    break;
                }
            }

            if (!found)
            {
                SPEventReceiverDefinition itemAdding = list.EventReceivers.Add();

                //the next line is only valid if the event receiver class is in the same assembly as the feature event receiver!!!
                itemAdding.Name = EVENT_RV_NAME;
                itemAdding.Assembly = System.Reflection.Assembly.GetExecutingAssembly().FullName;
                itemAdding.Class = strEventReceiverClassName;
                itemAdding.SequenceNumber = 1002;

                //you may add more “received” events in the following line.
                itemAdding.Type = eventReceiverType;
                itemAdding.HostId = list.ID;
                itemAdding.HostType = SPEventHostType.List;
                itemAdding.Update();
                list.Update();
            }
        }
    }

    public static void RemoveItemEventReceiver(SPList list, string strEventReceiverClassName)
    {
        if (list != null)
        {

            SPEventReceiverDefinitionCollection eventReceiverDefinitionCollection = list.EventReceivers;
            IList<Guid> eventRVIDs = new List<Guid>();
            foreach (SPEventReceiverDefinition item in eventReceiverDefinitionCollection)
            {
                eventRVIDs.Add(item.Id);
            }
            foreach (Guid eventRCID in eventRVIDs)
            {
                if (list.EventReceivers[eventRCID].Class.Equals(strEventReceiverClassName, StringComparison.InvariantCultureIgnoreCase))
                {
                    list.EventReceivers[eventRCID].Delete();
                }
            }
            list.Update();
        }
    }
}

Comments

Popular posts from this blog

Setup SharePoint 2010

Register CSS to SP Master Page