Tuesday, August 18, 2009

How to avoid recursive calls in list item event receivers in SharePoint

I wanted to insert a value into a column in a list when adding and updating items in the same list.

First I registered the item event receiver into the list.

SPList list = web.Lists[listName];
list.EventReceivers.Add(eventType, assemblyName, className);

Then in the actual event receiver class I override the “ItemAdded” and “ItemUpdated” methods.



public override void ItemAdded(SPItemEventProperties properties)
{
SPListItem item = properties.ListItem;
string itemStatusValue = string.Format("Item added @ {0} by {1}", DateTime.Now.ToLocalTime(),
properties.UserLoginName);
item["columnName"] = itemStatusValue;

item.Update();
}

public override void ItemUpdated(SPItemEventProperties properties)
{
SPListItem item = properties.ListItem;
string itemStatusValue = string.Format("Item updated @ {0} by {1}", DateTime.Now.ToLocalTime(),
properties.UserLoginName);
item["columnName"] = itemStatusValue;

item.Update();
}

But when I debug this in VS2008 I noticed that, as the item get updated or added it always calling to the “ItemUpdated” method.Of course that is understandable since I am updating a column in the same list.

But I didn’t want that to happen.Then I found out that you can enable/disable event firing.

So the solution for that is ,

DisableEventFiring();
item.Update();
EnableEventFiring();

It is pretty straight forward once you get to know it.

More references on this : Visit BinaryJam

1 comment:

Indika Rathnasekara said...

Here are some more info on this
http://feedproxy.google.com/~r/Binaryjam/~3/8mZaa04PnO4/

Thank you Mads for sending this link