2

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
  • 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. Commented Dec 18, 2017 at 10:25

2 Answers 2

2

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 } } } 
2
  • Thanks, it worked (and sorry for being late to respond). Commented Jan 24, 2018 at 12:56
  • thats fine, glad i could help! Commented Jan 25, 2018 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 } } 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.