954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Selecting a child node in treeview by [Index]

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

Sean87
Newbie Poster
5 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

TreeView.Nodes[1].Nodes[1]

Momerath
Nearly a Senior Poster
3,386 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558
 

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?

Sean87
Newbie Poster
5 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

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 :)

Momerath
Nearly a Senior Poster
3,386 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: