Recommended way now is to use new property EventFiringEnabled. This gives us an option to check current status and save it. I found a great post from Adrian Henke and modified his code using this new feature.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DisabledItemEventsScope : SPItemEventReceiver, IDisposable | |
{ | |
private bool eventFiringEnabledStatus; | |
public DisabledItemEventsScope() | |
{ | |
eventFiringEnabledStatus = base.EventFiringEnabled; | |
base.EventFiringEnabled = false; | |
} | |
#region IDisposable Members | |
public void Dispose() | |
{ | |
base.EventFiringEnabled = eventFiringEnabledStatus; | |
} | |
#endregion | |
} |
The class DisabledItemEventsScope disable/enable event firing for the current thread and could be used in that manner at any place including code behind for the page or web part
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
item["Title"]="New Title"; | |
using (new DisabledItemEventsScope()) | |
{ | |
item.Update(); // will NOT fire events | |
} |
BTW: There are couple useful SPList extensions to manage SPListItemEventReceiver collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sample: | |
// list.AddEventReceivers(typeof(TestProject.ListItemEventReceivers.TestReceiver), | |
// SPEventReceiverType.ItemAdded, SPEventReceiverType.ItemUpdated); | |
public static void AddEventReceivers(this SPList list,Type erClassType, | |
params SPEventReceiverType[] erTypes) | |
{ | |
foreach (SPEventReceiverType erType in erTypes) | |
{ | |
list.EventReceivers.Add(erType, erClassType.Assembly.FullName, | |
erClassType.FullName); | |
} | |
} | |
// Sample: | |
// list.RemoveEventReceivers(typeof(TestProject.ListItemEventReceivers.TestReceiver)); | |
public static void RemoveEventReceivers(this SPList list, Type erClassType, params SPEventReceiverType[] erTypes) | |
{ | |
List<SPEventReceiverDefinition> receivers = new List<SPEventReceiverDefinition>(); | |
for (int i = 0; i < list.EventReceivers.Count; ++i) | |
{ | |
SPEventReceiverDefinition r = list.EventReceivers[i]; | |
if (r.Class.Equals(erClassType.FullName) && (erTypes.Length==0 || erTypes.Contains(r.Type))) | |
receivers.Add(r); | |
} | |
foreach (SPEventReceiverDefinition r in receivers) | |
{ | |
r.Delete(); | |
} | |
} | |
good post, I used your class, thank you!
ReplyDelete