I always forget this and when I come to create a new SharePoint Event Receiver I wonder why theBeforeProperties or AfterProperties are sometimes not populated.
Consider an example, we need to handle the ItemUpdating event for a document library and prevent a user from changing a certain column. The code might look like this:
public override void ItemUpdating(SPItemEventProperties properties)
{
if (properties.BeforeProperties["Title"] != properties.AfterProperties["Title"])
{
properties.Cancel = true;
properties.ErrorMessage = "This column cannot be changed";
}
}
For a document library, this works just fine. For documents, Before and After properties are guaranteed for post events, such as ItemUpdating and ItemUpdated, but Before properties are not available for post events on list items.
The Before/After properties works differently between LIST and DOCUMENT LIBRARY
SharePointList
SharePointDocument Library
Properties.ListItem refers to the current list item values at this point in the event.
Original Value refers to the value which is already existing in the content DB.
New Value refers to the value which is being added newly in add event.
Changed Value refers to the value which is being updated in Update event.
So, if we go back to our original problem listed above. How can we prevent a user from changing a certain column for an item in a list event? From the list table, you can see if we hook into the ItemUpdating event, we can compare the current item’s value (properties.ListItem) to the AfterProperties value. The code would look like this:
// SPListItem item= properties.ListItem;
// String oldvalue=item[“Title”].ToString();
if (properties.ListItem["Title"] != properties.AfterProperties["Title"])
{
properties.Cancel = true;
properties.ErrorMessage = "This column cannot be changed";
}
Hope it Helps..
|
Contributing Knowledge about Microsoft Technology (.NET, SharePoint and many more)
Thursday, July 14, 2016
Working with BeforeProperties and AfterProperties on SPItemEventReceiver
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment