retrieving root node of treeview
Hello everyone,
Perhaps someone can help:
I am using a System.Windows.Forms app that has a treeview in it.
How do I retrieve the root node of a selected treenode?
Let's say I have a treeview:
GrandParent0
Parent0
child0
child1
child2
subchild0
Parent1
Parent2
So lets say I select subchild0. By using TreeView.SelectedNode, how can I retrieve its Parent0?
Thanks.
Regards,
# 1 Re: retrieving root node of treeview
You'll need to code this up manually as there isn't anything in the framework that allows you to backup to a specific node in the hierarchy (other than the root node of the control).
You'll have to walk back up calling currentTreeNode.Parent repeatedly to find the node you are interested in. You'll probably have to save the type of node you are storing, so you know whether to back up one, two, or ? nodes.
Something like:
// For subChild nodes
protected TreeNode RootNode
{
get
{
TreeNode rootNode = this.Parent;
if( null != rootNode )
{
return rootNode;
}
return null;
}
}
// For child nodes
protected TreeNode RootNode
{
get
{
return this.Parent;
}
}
Arjay at 2007-11-9 11:37:03 >

# 2 Re: retrieving root node of treeview
I thought about running through all the .Parents to find out the needed node as well, but I did not know how to do that :)
Thank you very verymuch for this.
One last question though, I apologyse: what you wrote here are properties right? I am trying to see how to use the code but I think I have to research properties a bit :)
Thank you once again.
Regards,
Andrei
# 3 Re: retrieving root node of treeview
What I would do is derive a couple of classes from the TreeNode class and supply an appropriate RootNode property for each type of class.
You can figure out some better class names, but something like (each of which are derived from TreeNode): ParentTreeNode, ChildTreeNode, and SubChildTreeNode. As mentioned each would contain a RootNode property.
The benefit to this is that when you are cycling through tree nodes, all you need to do is call RootNode no matter which node you are on. It makes the code cleaner this way.
Arjay at 2007-11-9 11:39:04 >

# 4 Re: retrieving root node of treeview
// For subChild nodes
...
// For child nodes
...
You should be able to do this for any node depth using the Level property:private TreeNode GetRootNode(TreeNode MyNode)
{
TreeNode RootNode = MyNode;
for (Int32 iLevel = 0; iLevel < MyNode.Level; iLevel++)
{
RootNode = RootNode.Parent;
}
return RootNode;
}
zips at 2007-11-9 11:39:59 >

# 5 Re: retrieving root node of treeview
perfect.
adjusted the method a bit, since for the Parent0, it needed in the for loop :
iLevel < MyNode.Level-1
and it works great.
thank you both for you help, this took me 2 days of brainstorming, really appreciate the solutions.
regards,
Andrei