Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}    
like image 618
LEMUEL ADANE Avatar asked Dec 23 '10 16:12

LEMUEL ADANE


1 Answers

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.

like image 192
digEmAll Avatar answered Oct 13 '22 20:10

digEmAll