TreeView control - auto check parent node - vb.net

Hi everyone,
I have a TreeView control with checkboxes. I would like to make sure that when I click a child node, the parent node will automatically be checked also - and vice versa.
How can this be done in vb.net?

Thanks in advance!!!
nahumbaAsked:
Who is Participating?
 
Bart-De-BalConnect With a Mentor Commented:
This checks the parent and the children of the selected item.

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim objTreeNode As System.Windows.Forms.TreeNode = tvwTest.Nodes.Add("test1").Nodes.Add("Test1.1").Nodes.Add("Test1.1.1")

        objTreeNode.Nodes.Add("Test1.1.1.1")
        objTreeNode.Nodes.Add("Test1.1.1.2")
        objTreeNode.Nodes.Add("Test1.1.1.3")
        objTreeNode.Nodes.Add("Test1.1.1.4")
        objTreeNode.Nodes.Add("Test1.1.1.5")
        objTreeNode.Nodes.Add("Test1.1.1.6")
        objTreeNode.Nodes.Add("Test1.1.1.7")

        tvwTest.Nodes.Add("test2").Nodes.Add("Test2.1")
    End Sub

    Private Sub tvwTest_AfterCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles tvwTest.AfterCheck
        If e.Action <> TreeViewAction.ByKeyboard And e.Action <> TreeViewAction.ByMouse Then
            Exit Sub
        End If
        If Not e.Node.Parent Is Nothing Then
            e.Node.Parent.Checked = e.Node.Checked

            For Each objTreeNode As System.Windows.Forms.TreeNode In e.Node.Nodes
                objTreeNode.Checked = e.Node.Checked
            Next
        End If
    End Sub
0
 
Bart-De-BalCommented:
Is this what you want ?

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        tvwTest.Nodes.Add("test1").Nodes.Add("Test1.1")
        tvwTest.Nodes.Add("test2").Nodes.Add("Test2.1")
    End Sub


Private Sub tvwTest_AfterCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles tvwTest.AfterCheck
        If Not e.Node.Parent Is Nothing Then
            e.Node.Parent.Checked = e.Node.Checked
        End If
    End Sub
0
 
nahumbaAuthor Commented:
Hi Bart-De-Bal,
Yes - almost - I forgot to mention that I'd like all child nodes to be checked also, not just the current node and it's parent.

Thanks!
0
 
SanclerCommented:
Here's code to handle the latter part of that

http://msdn2.microsoft.com/en-us/library/system.windows.forms.treeview.beforecheck.aspx

But read the notes carefully.  As they say, altering other nodes' check in one node's BeforeCheck or AfterCheck can cause recursive firing.  This node's parent is checked, which causes that node's parent to be checked, and all children are checked, etc.

Roger
0
All Courses

From novice to tech pro — start learning today.