How to get the last node of a TreeView
-
If you mean the last child, then: someParentTreeNode.LastNode or int c = treeView1.Nodes.Count treeView1.Nodes[c-1];
-
If you mean the last child, then: someParentTreeNode.LastNode or int c = treeView1.Nodes.Count treeView1.Nodes[c-1];
Thx for replying but that wont work i = Tree.GetNodeCount(true) will return the number of nodes in the tree including the sub trees, but Nodes[i] will throw an exception as Node.Nodes contains only the nodes in the node collection of the node Im searching (yeah its confusing). Say the tree has 500 nodes but only 4 at first level, doing this: n = Tree.GetNodeCount(true); TreeNode last = Tree.Nodes[n]; // exception because Tree.Nodes has 4 elements and Im trying to get the 500th. what I need is the LAST node in the last level of the tree.
-
Thx for replying but that wont work i = Tree.GetNodeCount(true) will return the number of nodes in the tree including the sub trees, but Nodes[i] will throw an exception as Node.Nodes contains only the nodes in the node collection of the node Im searching (yeah its confusing). Say the tree has 500 nodes but only 4 at first level, doing this: n = Tree.GetNodeCount(true); TreeNode last = Tree.Nodes[n]; // exception because Tree.Nodes has 4 elements and Im trying to get the 500th. what I need is the LAST node in the last level of the tree.
Well, then you may need to use recursion. You can try something like this to get to the deepest node of the tree: private void DepthSearch(TreeNodeCollection nodes, int depth) { int newDepth = depth; for(int i = 0; i < nodes.Count; i++) { if(nodes[i].NextNode == null) { //your code here; } newDepth++; this.TreeSearch(nodes[i].Nodes, newDepth); } } so, calling DepthSearch(TreeView.Nodes, 0) and inserting code (where it says 'your code') that populates some data structure with the current node and the depth, should give you the ability to compare the depths and choose the deepest node.
-
TreeView1.Nodes[TreeView1.Nodes.Count - 1];