简体   繁体   English

你调用的对象是空的。 (C#)

[英]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: 如果此方法中的逻辑是从事件处理程序(如Button_Click )运行的,那么它可以正常工作,但是,当从下面的方法运行它时,我得到错误:

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

也许没有选定的节点:)

Probably because no node is currently selected in the hostView TreeView. 可能是因为hostView TreeView中当前未选择任何节点。

The documentation says that the TreeView.SelectedNode property will return null when no node is currently selected. 文档说当没有当前选择节点时, TreeView.SelectedNode属性将返回null And since you've combined it into an expression, the entire expression is failing because there is no Nodes collection on a null object! 因为你把它组合成一个表达式,整个表达式都失败了,因为null对象上没有Nodes集合!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM