Mike
Mike

Reputation: 2386

Object reference not set to an instance of an object. (C#)

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

Upvotes: 0

Views: 2961

Answers (2)

Cody Gray
Cody Gray

Reputation: 244732

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

Upvotes: 1

Ana Betts
Ana Betts

Reputation: 74654

Maybe there are no Selected Nodes :)

Upvotes: 1

Related Questions