NullReferenceException on String Property

Total Post:101

 1527  View(s)
Rate this:

In my program I allow the user to add to a Data Collection bound to a TreeView. When the user creates the new node they are allowed to assign it a name. The user writes the nodes name in a textBox located in a pop up window. The text from the text box is bound to a property in a ViewModel.

However, I can't seem to get the property or the string in the ViewModel to read the value that it is bound to. It just shows up in the debugger as null, which is when I get the exception. I've created other windows exactly like this, but for some reason this one doesn't want to work.


<TextBox Text="{Binding TransName}" MaxHeight="20" MinHeight="20" Height="20" Margin="142,24,12,40" Name="textBox1" TextChanged="textBox1_TextChanged"></TextBox>

In the View Model:

private string _nodeName;

//Property for Node Name

public string NodeName


     get { return _nodeName; }



         _nodeName = value;

         NotifyPropertyChange(() => NodeName);



Still in the View Model, this is the line in which the Exception occurs

//hasSpace is a boolean

hasSpace = _nodeName.Contains(" ");

  1. Post:378

    Re: NullReferenceException on String Property

    Hi Pravesh,

    One possible solution is to use the property instead of the backing field. This will control what kind of output can be returned and eliminate the NullReferenceException.

    Change the property to return empty by default.

    public string NodeName
         get { return _nodeName ?? string.Empty; }
             _nodeName =value;
             NotifyPropertyChange(() => NodeName);

    Then change the ViewModel to use the property:

    hasSpace = NodeName.Contains(" ");

      Modified On Mar-31-2018 01:17:36 AM



Enter your email address here always to be updated. We promise not to spam!