Tuesday, June 25, 2013

BeforeProperties and AfterProperties in Sharepoint Event Receivers

Many of us have used BeforeProperties and AfterProperties while working with Event Receiver, but we don't know how and when to use these properties while accessing the data/field value.

These are facts we need to consider while working with Event receiver.

1) We should not use Before properties for accessing change of value at List level.
2) Before properties are available only with Document Library


I am summarizing about BeforeProperties, AfterProperties and properties.ListItem in sharepoint event receiver context.

List:
ListBeforePropertiesAfterPropertiesproperties.ListItem
ItemAddingNo valueNew valueNull
ItemAddedNo valueNew valueNew value
ItemUpdatingNo valueChanged valueOriginal value
ItemUpdatedNo valueChanged valueChanged value
ItemDeletingNo valueNo valueOriginal value
ItemDeletedNo valueNo valueNull

Library:

LibraryBeforePropertiesAfterPropertiesproperties.ListItem
ItemAddingNo valueNo valueNull
ItemAddedNo valueNo valueNew value
ItemUpdatingOriginal valueChanged valueOriginal value
ItemUpdatedOriginal valueChanged valueChanged value
ItemDeletingNo valueNo valueOriginal value
ItemDeletedNo valueNo valueNull


Here one more scenario we need to consider before we conclude this topic.

I have one example where I need to prevent the user from entering the same value for a column.

Ex: Suppose column called Description and its initial value is "Test" and user go to the list and update the item for that column with the same value we need to prevent this. How to achieve this?

So if we observe carefully with above table then we have answer available immediately.
In the ItemUpdating Event we can check the condition like

if(properties.ListItem["Description"] != properties.AfterProperties["Description"])
{
         //Cancel the event
         properties.Cancel = true;
         properties.ErrorMessage = "The column is having same original value";
}


 

7 comments:

  1. The code should be like this for given scenario..

    if(properties.ListItem["Description"] == properties.AfterProperties["Description"])
    {
    //Cancel the event
    properties.Cancel = true;
    properties.ErrorMessage = "The column is having same original value";
    }

    ReplyDelete
  2. You seemed to have stolen this blog post from someone else: http://www.sharepointalex.co.uk/index.php/2010/06/beforepropertiesafterproperties-in-event-receivers-i-always-forget-this/

    ReplyDelete
    Replies
    1. look at the library and list values delivered --> not stolen and your link gives wrong or at least not 100% correct information

      Delete
  3. This comment has been removed by a blog administrator.

    ReplyDelete