Reputation: 291
I am trying to set the value of a field on a ListItem in an event receiver but its not working
All i am doing during the event is
properties.AfterProperties[<field internal name>] = 1;
No errors are thrown but the the field i'm setting does not change. I have also tried
properties.ListItem[<field internal name>] = 1;
properties.ListItem.Update();
Have also tried SystemUpdate();
I know i am meant to be setting the afterproperties but think i am missing an obvious step.
Thanks
Upvotes: 3
Views: 26351
Reputation: 335
It is nice to update Title in ItemAdding and ItemUpdating events since extra Updates are avoided (without DisableEventFiring), and the "Edit Properties view" will already have the Title filled in
Some code example to update title based on filename. Works for Document Library and Picture Library. For working with Title in Lists, ["Title"] needs to be used.
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
string currTitle = properties.AfterProperties["vti_title"] as string;
string url = properties.AfterUrl;
var name = url.Substring(url.LastIndexOf('/') + 1);
//NOTE! Name is only copied to Title if title is not set. Will not handle name changes!
if (string.IsNullOrEmpty(currTitle))
{
properties.AfterProperties["vti_title"] = name;
}
}
Upvotes: 0
Reputation: 129
You can update values of a field in ItemUpdating also, this works for me.
properties.AfterProperties["FieldName"] = "computedvalue";
base.EventFiringEnabled = false; properties.ListItem.SystemUpdate(false);
base.EventFiringEnabled = true;
Upvotes: 0
Reputation: 194
You can add the value in the Item Adding event using the AfterProperties.ListItem[]=;
Upvotes: 1
Reputation: 7056
Keep in mind, that depending on whether your event receiver runs on a list or library you may need to use different properties (see this link for more info).
Assuming you are in the ItemUpdating
method running on a list, all you should need is:
base.ItemUpdating(properties);
properties.AfterProperties["InternalName"] = 1;
(no updates required since you are changing the value before it gets saved)
I would verify that your Event Receiver is attached to the list. Are you able to debug your Event Receiver when you modify an item in the list?
Upvotes: 11
Reputation: 6988
By the way, do not forget to call DisableEventFiring, because guess what happens when you call Update method? ItemUpdated event gets called again and you go into an endless loop...
Upvotes: 2
Reputation: 6859
The ItemUpdating is used for validation. If you want to set the values of fields, do it in the ItemUpdated event instead.
Upvotes: 0