setting check box for all child nodes in a tree view (VB.NET).

grambowk used Ask the Experts™

I'm using a tree view control in VB.NET to display the directory structure across all my disk drives.  This I have done successfully.

Now,  I'm also using check boxes on each node.  The idea being that if I check one of the boxes then every check box lower down in the hierarchy will also be checked.  This is where I'm stuck.

How can I check every check box on each child node (and subsequent child node)?

I have tried using the BeforeCheck event but the problem is that when I programmatically check the child node, this fires off the very same BeforeCheck event.

Any ideas or suggestions as to how I can do this would be most welcome.  Please bear in mind that my competence level with VB.NET is basic.


Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
You could check recursively the child nodes. I presume the event "BeforeCheck" is called with the node being checked as parameter or something. So all you have to do is browse its children and check them.
In the handler you will have to unsubscribe and then resubscribe to the BeforeCheck event...

Protected Sub TreeView1_BeforeCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeCheck
    RemoveHandler TreeView1.BeforeCheck, AddressOf Me.TreeView1_BeforeCheck
    CheckChildren(e.Node, Not e.Node.Checked)
    AddHandler TreeView1.BeforeCheck, AddressOf Me.TreeView1_BeforeCheck
End Sub

This is a recursive method which is called from the BeforeCheck event handler to check a node and all it's children and it's children's children, etc...

Protected Sub CheckChildren(ByVal node As TreeNode, ByVal checked As Boolean)
    If node.Nodes.Count > 0 Then
        Dim child As TreeNode
        For Each child In node.Nodes
            child.Checked = checked
            CheckChildren(child, checked)
    End If
End Sub



that worked perfectly.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial