C# – How to find a root node in TreeView

ctreeviewwinforms

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')?

Best Answer

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