Trying to use a Treeview with checkboxes to get child nodes to be marked checked when parent node is

J

Jack

Hello,

I am trying use a TreeView with checkboxes. I would like to check more than
one node and allow all child nodes of selected nodes to be checked or
unchecked with the parent is checked.

Thanks in advance for any help,

Jack
 
G

Guest

Put this code for the AfterCheck Event for the Tree in your application. It
will recursively call itself until all levels under the tree node that was
checked are also checked.

Private Sub myTree_AfterCheck(ByVal sender As Object, ByVal e As _
System.Windows.Forms.TreeViewEventArgs) Handles MyTree.AfterCheck
Dim t As TreeNode
For Each t In e.Node.Nodes
t.Checked = e.Node.Checked
Next
End Sub
 
K

Kai Zhang

Here is another approach:
The following code will allow you to
1. check / uncheck all the children nodes when you check/uncheck parent
node.
2. auto check the parent node if all of its child nodes are checked.
3. auto uncheck the parent node if one of its child node is uncheck.


'\\\
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
'///

HTH,

Kai
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top