views:

37

answers:

1

I am trying to create a treeview that looks something like the following:

Parent

|__Child1

|__ __ __ O Grandchild1

|__ __ __ O Grandchild2

|__Child2

|__ __ __ O Grandchild3

|__ __ __ O Grandchild4

I am using vb.net in Visual Studio 2008. Any insights as to how I can accomplish this will be very much appreciated!

A: 

You cannot have radio buttons in a TreeView, only checkboxes.

A solution would be to make the checkboxes behave like radio buttons:

Private Sub TreeView1_AfterCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterCheck
    If e.Node.Checked Then
        If e.Node.Level = 2 Then
            For Each node As TreeNode In e.Node.Parent.Nodes
                If node IsNot e.Node Then
                    node.Checked = False
                End If
            Next
        Else
            e.Node.Checked = False
        End If
    End If
End Sub

The e.Node.Level = 2 check makes sure only grandchild nodes behave like radio buttons.

Set the TreeView's CheckBoxes property to True to enable checkboxes.

This is an example of how to change text style of selected nodes and its parents:

Private Sub TreeView1_BeforeSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeSelect
    If TreeView1.SelectedNode IsNot Nothing Then
        MakeSelected(TreeView1.SelectedNode, False)
    End If
    MakeSelected(e.Node, True)
End Sub

Private Sub MakeSelected(ByVal node As TreeNode, ByVal selected As Boolean)
    Dim SelectedFont As New Font(TreeView1.Font, FontStyle.Bold)
    node.NodeFont = IIf(selected, SelectedFont, TreeView1.Font)
    node.ForeColor = IIf(selected, Color.Blue, TreeView1.ForeColor)

    If node.Parent IsNot Nothing Then
        MakeSelected(node.Parent, selected)
    End If
End Sub

It recursively changes the text style of the selected node and its parents and sets it back to the TreeView's default style when the selection changes.

Arjan
Thank you for your feedback Arjan. The reason I hadn't set the TreeView's CheckBoxes property to true in the first place was because I didn't want them to appear in the parent and child nodes (just the grandchildren). I also want to change the text colour of the selected node and the nodes that it decends from. For example, if Grandchild3 is selected, I would like to see its text in bold blue as well as that of Child2 and Parent.
8thWonder
Sadly, checkboxes can only be enabled and disabled for all nodes, but when you use my example, the checkboxes of the parent and child nodes cannot be checked.
Arjan
I added an example of how to change text style of selected nodes and its parents.
Arjan