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

advertisements

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


Maybe there are no Selected Nodes :)