Remove an Event Receiver in SharePoint

Everyone and their brother shows you the quick and dirty method on how to add an event receiver to a list.  Not many people show you how to remove them (Not even some of the Microsoft Press books…)  There are 2 ways.. if you have the GUID of your event receiver, instantiate an instance of  an SPEventReceiverDefintion object with that guid and then delete it.  Else, here’s the long way: (I’m going under the assumption that you’re a good MOSS/WSS programmer and using Features to deploy your event handler…)

public override void FeatureDeactivating(SPFeatureReceiverProperties properties){

 using (SPWeb web = (SPWeb)properties.Feature.Parent){

SPDocumentLibrary proposals = (SPDocumentLibrary)web.Lists["test"];
SPEventReceiverDefinitionCollection erdc = proposals.EventReceivers;
SPEventReceiverDefinition erd = null;
bool found = false;

for (int i = 0; i < erdc.Count; ++i){
erd = erdc[i];
if (erd.Assembly == asmName && erd.Type == SPEventReceiverType.ItemAdded){
found = true;
break;}
}
if (found)
erd.Delete();
}
}

你可能感兴趣的:(SharePoint)