Home > DeveloperSection > Forums > NullReferenceException on String Property
Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    September-21-2013 7:03 AM

 WPF
Ratings:


 1 Reply(s)
 850  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.

XAML:

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

     set

     {

         _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(" ");



Sumit Kesarwani

Total Post:378

Points:2694
Posted on    September-21-2013 7:58 AM

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

     set

     {

         _nodeName = value;

         NotifyPropertyChange(() => NodeName);

     }

}

Then change the ViewModel to use the property:

hasSpace = NodeName.Contains(" ");


Don't want to miss updates? Please click the below button!

Follow MindStick