Pergunta

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?

Foi útil?

Solução

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
        }
    }
}

Outras dicas

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
    }           
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a sharepoint.stackexchange
scroll top