Tuesday, April 24, 2007

How to stop SpListItem.Update() method from recursively calling the ItemUpdated() event handler

When updating a SharePoint 2007 List Item within a custom event handler "ItemUpdated", we need to invoke the Update() method of the ListItem to commit changes to the MOSS DB. However when you invoked the Update() method within the "ItemUpdated" event handler, it triggers a recursive loop and keeps triggering the event again and again. For example:


public override void ItemUpdated(SPItemEventProperties properties)
{
SPListItem curListItem = properties.ListItem;
curListItem["Title"] = "Test";

curListItem.Update(); // This line triggers the event to fire again recursively

}

A possible solution is to use the Enable/Disable Event Firing methods available on the SPListItem object. For example:

public override void ItemUpdated(SPItemEventProperties properties)
{
SPListItem curListItem = properties.ListItem;
curListItem["Title"] = "Test";

curListItem.DisableEventFiring(); // Disables event firing temporarily before performing update

curListItem.Update(); // This line triggers the event to fire again recursively

curListItem.EnableEventFiring(); // Enables event firing once update is complete
}

10 comments:

  1. Anonymous4:44 pm

    I tried using your code but couldn't find the Disable & enable method you have written for the event handler. i am trying to write the code in custom control class . not in an event handler. let me know if there is another way of doing this.

    ReplyDelete
  2. This is because the DisableEventFiring() method is part of SPEventReceiverBase and additionaly it's a protected method of that class....

    ReplyDelete
  3. Anonymous1:59 am

    Does this disabling happen just within the context of this instance of this item being updated, or does it disable event firing for all instances of this/any item being updated?

    I hope its only for the first case above.

    ReplyDelete
  4. Anonymous8:18 pm

    I wish people who put rubbish like this on the internet would stop, or at least correct it.

    If it is inside a regular event handler (based on SPItemEventReceiver as Gavin stated) then the lines should read:

    this.DisableEventFiring();
    &
    this.EnableEventFiring();

    Keep cowboys away from Sharepoint!

    ReplyDelete
  5. Anonymous2:41 pm

    Hello all,

    I am adding ListItems thru code.
    I have written some code for ItemAdded Event to do somework.
    But I want to temporarely stop the event Triggering, when i am adding the ListItems thru Code.
    Is it Possible?
    Thanks In advance.

    ReplyDelete
  6. Anonymous5:06 pm

    I do not think they are cowboys, i think they are just plan retards!

    ReplyDelete