locked
Getting hold of a specific node within a TreeView structure RRS feed

  • Question

  • Hiya,

    I'm struggling to get my head around how to reference individual nodes within a TreeView structure.

    The help says:

    TreeNode TreeNodeCollection [string key]
    key: the name of the System.Windows.Forms.TreeNode to retrieve from the collection

    So in the bellow example I'm attempting to reference an existing node to add a subnode bellow it, but the referencing method I'm using doesn't appear to work.

    I'm assuming it's because I'm misinterpreting what 'key' actually is, but I'm not sure how I should interpret it.

    The bellow code will fail at "foreach (TreeNode node in treeView1.Nodes[reseller].Nodes)" stating "Object reference not set to an instance of an object."

    Code Block

            private void addNode(String reseller, String account, String user)
            {
                // Need an account node at the first level of the treeview first of all..
                bool found = false;
                // first check to see if 'reseller' node already exists
                foreach (TreeNode node in treeView1.Nodes)
                {
                    if (node.Text.ToString() == reseller)
                    {

    // already exists, don't need to create it

                        found = true;

                    }
                }

                if (!found)
                {
                    // create reseller node
                    TreeNode node = new TreeNode();
                    node.Text = reseller;
                    treeView1.Nodes.Add(node);
                }

                // Now we can create a subnode of 'reseller' called 'account'
                found = false;
                // first check to see if 'account' already exists
                foreach (TreeNode node in treeView1.Nodes[reseller].Nodes)
                {
                    if (node.Text.ToString() == account)
                    {

    // already exists, don't need to create it.

                   found = true;

                    }
                }

                if (!found)
                {
                    TreeNode node = new TreeNode();
                    node.Text = account;
                    treeView1.Nodes[reseller].Nodes.Add(account);
                }
            }

    Tuesday, January 22, 2008 10:57 AM

Answers

  • Hiya,

    Answering myself.. but I believe the cause of my confusion was to do with me confusing the 'text' and 'name' properties..

    The 'string key' in the definition above seems to be looking (quite obviously in retrospect!) the 'name' property rather than the text..

    Simply setting the 'name' property to the same value as the 'text' property in the above example got my 95% of the way to fixing things.
    Tuesday, January 22, 2008 9:16 PM