-1

I have a few buttons that send text string data from a textbox to a textblock on another page. Please see code below.

However, it only works when I press all of the buttons, whenever I press only one of them, I run into an error. (Please see below)

An exception of type 'System.NullReferenceException' occurred in WpfApplication4.exe but was not handled in user code Additional information: Object reference not set to an instance of an object.

Rogan
  • 47
  • 1
  • 6
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) –  Feb 06 '17 at 13:36

2 Answers2

1

The issue that Application.Current.Properties["obj1"] please use null propagation ?. to be sure that in case property is not set you will not try to call ToString() for it

textBlock.Text = Application.Current.Properties["obj1"]?.ToString();
klashar
  • 2,519
  • 2
  • 28
  • 38
  • or check if Application.Current.Properties.Contains("obj1") – Arie Feb 06 '17 at 12:37
  • @klashar Thank you very much... Worked perfectly – Rogan Feb 06 '17 at 13:54
  • @Rogan I think you will have to keep the previous value of the property somewhere (e.g. Application.Current.Properties["prev_obj1"]), and reassign it at "cancel" click, or keep the current in some temporary variable and asign it only on click that means "save". – Arie Feb 13 '17 at 06:40
0

If you just press button 1 then only obj1 is set and obj2 is not. Application.Current.Properties["obj2"] is therefore null.

As you are calling Application.Current.Properties["obj2"].ToString() this is the same as calling null.ToString() which is why you get a NullReferenceException.

If you are using VS 2015 or later you can use null propogation as klashar suggests otherwise you will need to use an if statement to check if the value is null before calling ToString()

apc
  • 5,306
  • 1
  • 17
  • 26