Mittwoch, 23. September 2009

Updating item in "ItemUpdating" event receiver

The usual case when implementing a synchronous event like "ItemUpdating" is validating the values. For example you can easily do:

public override void ItemUpdating(SPItemEventProperties properties)
{
if (properties.AfterProperties["column"] == "aValue"){
properties.Cancel = true;
properties.ErrorMessage = "This column cannot be 'aValue'";
}
}

But if you want to change a value of the item, you cannot do this by updating the item in the common way:

item["column"] = "aValue";
item.Update();

Due to the nature of the synchronous event which is not yet completed you will get an error stating a concurrency exception.
Also the following will not do the trick. It won't raise an exception but your value will be overridden when the event is completed.
So the solution will be to put the value in the 'AfterProperties' HashTable and let the event finish.

string internalName = properties.ListItem.Fields[FIELD_NAME].InternalName;
properties.AfterProperties[internalName] = "aValue";