How do I add a treenode with a key?

J

jmDesktop

I am trying to add nodes with keys to my treeview. I can add general
nodes without problem with:

//create new node
TreeNode newNode = new TreeNode(myIdNumber);

//create children
TreeNode myPersonNode = new TreeNode(myPerson);
TreeNode myAddressNode = new TreeNode(myAddress);

TreeNode[] myNodes = {myPersonNode, myAddressNode};

newNode.Nodes.AddRange(myNodes);

But now I want to interate throught them and stop when I am at a
certain node. I know I can iterate with:

private void PrintRecursive(TreeNode treeNode)
{
// adapted from msdn

//my nodes I'm testing for
if (treeNode.Index == 2 || treeNode.Index == 3)
MessageBox.Show(treeNode.Text);

// Print each node recursively.
foreach (TreeNode tn in treeNode.Nodes)
{

PrintRecursive(tn);
}
}

But using the index seems wrong. I read the docs where I can add a
key and text, but I can't figure out how to use it. I want to create
a node like above and when I add that node I want it to have a key so
I can find it with my recursive function. How can I find the node I
want besides using index? Thank you.
 
P

Pavel Minaev

I am trying to add nodes with keys to my treeview.  I can add general
nodes without problem with:

            //create new node
            TreeNode newNode = new TreeNode(myIdNumber);

            //create children
            TreeNode myPersonNode = new TreeNode(myPerson);
            TreeNode myAddressNode = new TreeNode(myAddress);

            TreeNode[] myNodes = {myPersonNode, myAddressNode};

            newNode.Nodes.AddRange(myNodes);

But now I want to interate throught them and stop when I am at a
certain node.  I know I can iterate with:

        private void PrintRecursive(TreeNode treeNode)
        {
            // adapted from msdn

            //my nodes I'm testing for
            if (treeNode.Index == 2 || treeNode.Index == 3)
                MessageBox.Show(treeNode.Text);

            // Print each node recursively.
            foreach (TreeNode tn in treeNode.Nodes)
            {

                PrintRecursive(tn);
            }
        }

But using the index seems wrong.  I read the docs where I can add a
key and text, but I can't figure out how to use it.  I want to create
a node like above and when I add that node I want it to have a key so
I can find it with my recursive function.  How can I find the node I
want besides using index?  Thank you.

If you want to associate some custom value with a TreeNode, that's
precisely what TreeNode.Tag is for.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top