Hi all,

I can't figure out how to select a child node when I already know its parent [Index] and the child's [Index] itself. Imagine a treeview like this:

+ Parent[0]
|--- Child [0]
|--- Child [1]
+ Parent[1]
|--- Child [0]
|--- Child [1]
|--- Child [2]

So how can I wrote a code to select (or find) the Child with index 1 from parent with index 1?

Thanks

Recommended Answers

All 3 Replies

TreeView.Nodes[1].Nodes[1]

Thanks a lot, you solved my current problem.

I am just wondering how this can be done when there are lots of childes, subchilds and more in the tree view?

You'd have to develop a method. For example:

public TreeNode GetNode(int[] pos) {
    TreeViewNodeCollection nodeCollection = myTreeView.Nodes;
    for (int i = 0; i < pos.Length - 1; i++) {
        nodeCollection = nodeCollection[pos[i]].Nodes;
    }

    return nodeCollection.Nodes[pos[pos.Length-1]];
}

Note: This is just off the top of my head, I may have things spelled wrong. It'll also throw exceptions if the child nodes don't exist.

A better method would be to recursively walk the node tree and find what it is you wanted, but you'd need a way to tell if you've found the one you want :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.