Tuesday, April 24, 2007

Updating SPListItem fields in the ItemAdded event or ItemUpdated event does not actually update the ListItem being updated

One common problems which lot of MOSS developers working on custom event handlers face is that their custom events like "ItemAdded" or "ItemUpdated" etc has code updating the various fields in the ListItem but after the "Update()" method is invoked, the new values are not updated in the ListItem. 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 should update the ListItem but it doesnt

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

For the update to go through, its mandatory to set "AllowUnsafeUpdates" property of the Web object with the SPListItem class to true. So the correct version of the above code is as follows:

public override void ItemUpdated(SPItemEventProperties properties)
{
SPListItem curListItem = properties.ListItem;

curListItem.Web.AllowUnsafeUpdates = true; // This property should be set to true for the update to go through

curListItem["Title"] = "Test";

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

curListItem.Update(); // This line should update the ListItem but it doesnt

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

2 comments:

Anonymous said...

As far as I noticed there is no DisableEventFiring() method in SPListItem class.

Unknown said...

Original ugg boots uk are first category in alter. They are so much appealing louboutin shoes so,