0

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

   }
JPJedi
  • 1,498
  • 7
  • 32
  • 58
  • What if the selected node is a descendant of another...does it hop back up the hierarchy and drill back into every successive layer? Or just the child nodes of the one you're on? – DonBoitnott Jun 05 '13 at 18:29
  • I want to make it start at the selected node and only drill down to the children nodes that are associated to the selected. So the selected node would be the top dog/pardent node and anything below it would be looped through. – JPJedi Jun 05 '13 at 18:34
  • Unless you know the depth (i.e. it's hard-coded somewhere and isn't going to change), you will need a recursive loop to drill to the bottom. A series of loops over `theCurrentNode.Nodes` until you reach the bottom. – DonBoitnott Jun 05 '13 at 18:37
  • I know the starting location of the node (treelevel, name and text) – JPJedi Jun 06 '13 at 16:32
  • Did my answer not work? If not, why? – DonBoitnott Jun 06 '13 at 16:41

2 Answers2

1

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

DonBoitnott
  • 10,787
  • 6
  • 49
  • 68
0

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.
        }
    }