Loop through nodes of tree view from current selected

5.7k views Asked by At

I have a tree view that has been built fine with no issues.

Is their a way to start looping through the nodes at the current selected node instead of looping through all of them?

TreeNodeCollection nodes = treeView.Nodes;
   foreach (TreeNode n in nodes)
   {

   }
2

There are 2 answers

0
DonBoitnott On

You could use an extension method to do this:

public static class TreeViewEx
{
    public static List<TreeNode> GetAllNodes(this TreeNode Node)
    {
        List<TreeNode> list = new List<TreeNode>();
        list.Add(Node);
        foreach (TreeNode n in Node.Nodes)
        list.AddRange(GetAllNodes(n));
        return list;
    }
}

Use it like this:

TreeNode node = myTree.SelectedNode;
List<TreeNode> list = node.GetAllNodes();

I should point out that the returned List will include the starting node (the one you selected originally).

0
AudioBubble On

This may help head you in the right direction you would need to check each child node to see if they had children:

    TreeView treeView = new TreeView();
    TreeNode parentNode = treeView.SelectedNode;

    if (parentNode.GetNodeCount(true) > 0)
    {
        foreach (TreeNode childNodes in parentNode.Nodes)
        {
            //// do stuff with nodes.
        }
    }