0

If the logic within this method is run from an event handler such as Button_Click it works perfectly, but, when running this from a method such as below I get the error:

hostView.SelectedNode.Nodes.Add(newNode);

Object reference not set to an instance of an object.

Here is my code:

private void SetupHostTree()
{
    // Set internal host names
    using (var reader = File.OpenText("Configuration.ini"))
    {
        List<string> hostnames = ParseInternalHosts(reader).ToList();
        foreach (string s in hostnames)
        {
            TreeNode newNode = new TreeNode(s);
            hostView.SelectedNode.Nodes.Add(newNode);

            string title = s;
            TabPage myTabPage = new TabPage(title);
            myTabPage.Name = s;
            tabControl1.TabPages.Add(myTabPage);
        }
    }
}
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
Mike
  • 2,266
  • 10
  • 29
  • 37
  • Please use the debugger and provide more information about where the error happened. – Felix K. Jan 14 '12 at 11:59
  • He gave all of that information in the question. Read it more carefully. – Cody Gray - on strike Jan 14 '12 at 12:05
  • @Mike - this type of error shows how exceptions occur. You're reading a config file and it's contents may not be exact. This is most likely not an exceptional circumstance and as such you code defensively - checking for nulls yourself where the content cannot be controlled. – Preet Sangha Jan 14 '12 at 12:05
  • possible duplicate of [What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) – John Saunders Jan 14 '12 at 12:05

2 Answers2

1

Maybe there are no Selected Nodes :)

Ana Betts
  • 73,868
  • 16
  • 141
  • 209
1

Probably because no node is currently selected in the hostView TreeView.

The documentation says that the TreeView.SelectedNode property will return null when no node is currently selected. And since you've combined it into an expression, the entire expression is failing because there is no Nodes collection on a null object!

Try this code:

private void SetupHostTree()
{
    // Set internal host names
    using (var reader = File.OpenText("Configuration.ini"))
    {
        List<string> hostnames = ParseInternalHosts(reader).ToList();
        foreach (string s in hostnames)
        {
            // Ensure that a node is currently selected
            TreeNode selectedNode = hostView.SelectedNode;
            if (selectedNode != null)
            {
                TreeNode newNode = new TreeNode(s);
                selectedNode.Nodes.Add(newNode);
            }
            else
            {
                // maybe do nothing, or maybe add the new node to the root
            }

            string title = s;
            TabPage myTabPage = new TabPage(title);
            myTabPage.Name = s;
            tabControl1.TabPages.Add(myTabPage);
        }
    }
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574