-1

I have a TreeView where I want to get NextNode so I do simple like:

var nextNode = e.Node.NextNode.Text;

If it have nextNode it returns value right. Problem if it comes null, application crash and throw

System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Windows.Forms.TreeNode.NextNode.get returned null.

Why application crash? should not return the null variable instead application crash?

Pepe
  • 111
  • 8

1 Answers1

3

It appears that an instance of NextNode does not exist yet you attempt to access the Text property.

You have two options:

  1. Retrieve the NextNode object and check for NULL
  2. Use the null coalescing operator to access the text or substitute it.

1 - Check for null

NextNode node = e.Node.NextNode;
string thetext = string.Empty;
if (node != null)
    thetext = node.Text

2 - Null coalescing operator

string thetext = e.Node?.NextNode?.Text ?? string.Empty;

They will both do the same thing. If NextNode is null then the variable thetext will contain an empty string, otherwise it will contain the Text of NextNode.

Handbag Crab
  • 1,488
  • 2
  • 8
  • 12