tags:

views:

24

answers:

1

I am trying to check all the childnodes under a parent node, the code I have so far only goes about 2-3 levels deep in the TreeView and I am looking to grab all nodes no matter how deep they are. Could someone shed some insight on this.

Below is the code:

Private Sub CheckChildNode(ByVal currNode As TreeNode) 'set the children check status to the same as the current node Dim checkStatus As Boolean = currNode.Checked For Each node As TreeNode In currNode.Nodes node.Checked = checkStatus CheckChildNode(node) Next End Sub

Private Sub CheckParentNode(ByVal currNode As TreeNode) Dim parentNode As TreeNode = currNode.Parent If parentNode Is Nothing Then Exit Sub parentNode.Checked = True For Each node As TreeNode In parentNode.Nodes If Not node.Checked Then parentNode.Checked = False Exit For End If Next CheckParentNode(parentNode) End Sub

Private Sub treeview_AfterCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles treeview.AfterCheck RemoveHandler treeview.AfterCheck, AddressOf treeview_AfterCheck CheckChildNode(e.Node) CheckParentNode(e.Node) AddHandler treeview.AfterCheck, AddressOf treeview_AfterCheck End Sub

A: 

In order to get all subnodes no matter how deep they are, you definitely need recursion.

That is, you take each direct child of a node and do the check for this node. And you also call the method to check subnodes for each child.

So here in Pseudocode.

node getParentNode(node child){
 return child.parent
}

node checkNode(node n){
 // perform check here for node n
 if n is not valid {
  return false!
 }
 // do children recursively
 for each child in n.children{
  // function calls itself!
  checkNode(child)
 }
}

Here's a recursion tutorial for vb.net. Here, here and here is you can find additional information.

phimuemue
Another way to have all nodes checked is to insert this code in your AfterCheck statment. Private Sub myTree_AfterCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles tvFiles.AfterCheck Dim t As TreeNode For Each t In e.Node.Nodes t.Checked = e.Node.Checked Next End Sub
jpavlov