7
votes

I have a TreeView in my Windows application. Tn this TreeView, the user can add some root nodes and also some sub nodes for these root nodes and also some sub nodes for these sub nodes and so on ...

For example:

Root1
     A
       B
         C
         D
          E  
Root2
     F
      G
.
.
.

Now my question is that if I am at node 'E' what is the best way to find its first root node ('Root1')?

2

2 Answers

13
votes

Here is a little method for you:

private TreeNode FindRootNode(TreeNode treeNode)
{
    while (treeNode.Parent != null)
    {
        treeNode = treeNode.Parent;
    }
    return treeNode;
}

you can call in your code like this:

var rootNode = FindRootNode(currentTreeNode);
0
votes
public TreeNode RootTreeNode(TreeNode n) { while (n.Level > 0) { n = n.Parent; } return n; } 

Example to get root treenode:

private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
    var node = (e == null ? ((System.Windows.Forms.TreeView)sender).SelectedNode : e.Node);
    var rootNode = RootTreeNode(node);
}

Enjoy