Question

So I'm trying to accomplish this kind of functionality on my SharePoint 2010 list:

I have a field of type choice in my list, which has 7 values and i want users not to be able to change the value of that field from values 2,3,4,5,6,7 to value 1.

I've written an event receiver for that list, here's my code:

public override void ItemUpdated(SPItemEventProperties properties)
   {
       base.ItemUpdated(properties);

       string beforeStatus = properties.BeforeProperties["Status"].ToString();
       string afterStatus = properties.AfterProperties["Status"].ToString();

       if (beforeStatus != "1stValue" && afterStatus == "1stValue")
       {
           properties.Cancel = true;
           properties.ErrorMessage = "This isn't allowed.";
       }
   }

I've tried using both ItemUpdated and ItemUpdating event receivers, when I was debugging I saw that the event receiver get's called as it should be, but beforeStatus and afterStatus is getting null from the item in both cases.

So, how can I get the values of the item's field before and after updating correctly? Thanks in advance!

Note: the field's internal and display names are both Status.

Was it helpful?

Solution

Use ItemUpdating event and then afterproperties contains changed value and ListItem contains original value of a field.

Here you can find info what properties are avaialable in each events.

It is also important how do you edit the list item. If via SharePoint default edit form all columns are present in afterproperties collection, but if you edit an item from custom code (e.g. webpart, event receive) only updated columns are present in that collection.

Edit: For good looking errors you can redirect user to custom error page (which you have to create)

properties.Cancel = true;
properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl; 
properties.RedirectUrl = "/_layouts/MySolution/CustomErrorPage.aspx?Error=" + errorMessage;

OTHER TIPS

I've found a solution to this by myself:

According to this article, I've found out that if I want to get both the old and new values, I have to use ItemUpdating event receiver and use properties.ListItem to get old values and properties.AfterProperties to get the new ones.

Although the error message looks awful to users: error

I will try to solve this now :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top