Monday, October 30, 2006

Preventing event handler recursion

One of the problems I had with list event handlers was event recursion.

I wrote an event handler to handle updating items. I wanted to check some values, and then set a value in a field based on a set of rules. The problem was- when I set the value of the field and updated the item, the ItemUpdated and ItemUpdating events fired up again, and again my code updated the item and so on and so on. I also wanted to avoid having the list item change version number following my code-update. that update was supposed to be part of the version that the user just created by updating. Otherwise, every user update of the list item would bump the version number twice! Similarily, I didnt want the code to show that an administrator changed the item. I wanted it to look as if the user did the change to that field.

So after some research, here is my solution: item[fieldnamehere] = fieldvaluehere; this.DisableEventFiriing(); item.SystemUpdate(false); this.EnableEventFiring();

This piece of code updates the item without firing the current event handler events, and doing the update using the SystemUpdate(false) method ensures that version number doesnt increase and the update is considered as if it was part of the user's update.


Lakshmikanth Reddy said...

Thanks for giving a good solution.
But its not works for me. Can you please help me where to keep your code in the following code:

public override void ItemDeleting(SPItemEventProperties properties)
// Collect the SPlistitem from the EventProperties

SPListItem anItem = properties.ListItem;

// Create a String to write an entry

string strMessage = "An Item is Deleted: " + anItem.Title.ToString() + ":" + anItem["Name"].ToString();

// Call the Log method create above.


AddLogEntry(strMessage, properties);


Thanks in advance......

Anonymous said...

You cannot do run code with Itemdeleting, the code only can be run under itemdeleted.
this momont. I think within itemdeleting, we can do cancel only.

Anonymous said...

This is a good idea. Unfortunately, in SharePoint 2007 Beta 2 TR, this is not working for me. My event still fires 2x. If you have any further suggestions, then please let us know. My code is below.

public override void ItemAdded(SPItemEventProperties properties)

// some work... move documents... copy documents... etc...

Common.Utility.LogMessage("Custom Message From ItemAdded.", "Event fired!", "ItemAdded was run.");


Anonymous said...

I use this as well with success. I do have a question though.

When a list item is updated in eventhandler code, the InfoPath promoted fields are cleared from the view. Is there a trick to prevent this?

Thanks in advance!

Arjen Kraak