1

I have created an event receiver to evaluate the value of a person field when the item is being updated and execute some code if it has been updated. The code is pretty simple and looks like this:

public override void ItemUpdating(SPItemEventProperties properties)
{
 base.ItemUpdating(properties);
    // Check if person field has been modified
    string currentValue = properties.ListItem["AssignedPerson"].ToString();
    string newValue = properties.AfterProperties["AssignedPerson"].ToString();

        if (currentValue != newValue)
        {
            // do something
        }
}

The receiver works fine if both current and new values are not blank, but if either is blank I'm getting a NullReferenceException.

Is there a proper way to check for blank person field values or should I just handle blank values before setting the string variables?

  • 1
    Apparently properties.ListItem["AssignedPerson"] is null if the field is left empty, and you cannot cast null to string. Only do properties.ListItem["AssignedPerson"].ToString() after verifying properties.ListItem["AssignedPerson"] is not null. – Jussi Palo Dec 18 '17 at 10:25
1

You need to check if its empty or null first before you use it:

Copy the whole code block below, comment out your code and run it to test:

public override void ItemUpdating(SPItemEventProperties properties)
{
 base.ItemUpdating(properties);
    // Check if person field has been modified
    string currentValue = properties.ListItem["AssignedPerson"].ToString();
    string newValue = properties.AfterProperties["AssignedPerson"].ToString();


    if (properties.ListItem["AssignedPerson"] == null || SPEncode.HtmlEncode(properties.ListItem["AssignedPerson"].ToString()) == string.Empty && properties.AfterProperties["AssignedPerson"] == null || SPEncode.HtmlEncode(properties.AfterProperties["AssignedPerson"].ToString()) == string.Empty)
    {
        //do nothing or show message that val is blank
    }
    else
    {
        if (currentValue != newValue)
        {
            // do something
        }
    }
}
  • Thanks, it worked (and sorry for being late to respond). – orestisf Jan 24 '18 at 12:56
  • thats fine, glad i could help! – Ali Jafer Jan 25 '18 at 11:51
1

Modify the code as below:

public override void ItemUpdating(SPItemEventProperties properties)
{
    base.ItemUpdating(properties);
    string currentValue = "";
    if (properties.ListItem["AssignedPerson"] != null) 
    {
        currentValue = properties.ListItem["AssignedPerson"].ToString();           
    }
    string newValue = properties.AfterProperties["AssignedPerson"].ToString();

    if (currentValue != newValue)
    {
        // do something
    }           
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.