开发者

check all items under a parent node in Visual Basic

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 a开发者_运维问答re. 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜