How do you get the root node or the first level node of the selected node in a tree view?

LEMUEL  ADANE picture LEMUEL ADANE · Dec 23, 2010 · Viewed 52.3k times · Source

Are there more straight forward method than the code below to get the root nodes or the first level nodes in a tree view?

TreeNode node = treeView.SelectedNode;

while(node != null)
{
       node = node.Parent;
}    

Answer

digEmAll picture digEmAll · Dec 23, 2010

Actually the correct code is:

TreeNode node = treeView.SelectedNode;
while (node.Parent != null)
{
    node = node.Parent;
} 

otherwise you will always get node = null at the end of the loop.

BTW, if you are sure to have one and one only root in your TreeView, you could consider to use directly treeView.Nodes[0], because in that case it would give the root.