• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 658
  • Last Modified:

TreeView Top Node name


I've a Treeview on a Winform, with this kind of structure:

Family 1
    Group 1
    Group 2
       Item 1
       Item 2
       Item 3

When I select Item 2, for example, I can get the name of the 2nd level node (in this case "Group 2") using trvMyTreeView.SelectedNode.Parent.Text. How can I get the name of the "family" (in this case "Family 1")?


1 Solution
Éric MoreauSenior .Net ConsultantCommented:
can you show your code?
use a loop to get the parent for a particular level eg.
Private Function GetParentNode(ByVal node As TreeNode, ByVal level As Integer) As TreeNode
    Dim tmp As TreeNode = node
    For n As Integer = 1 To level
        If (tmp.Parent Is Not Nothing) Then
            tmp = tmp.Parent
            ' Might want to do something here to say the level is too high?
            Return tmp
        End If
    Next n
    Return tmp
End Function

Open in new window

Jorge PaulinoIT Pro/DeveloperCommented:

You can do this:

Dim result As String = Me.Treeview1.SelectedNode.FullPath.Substring(0, Me.Treeview1.SelectedNode.FullPath.IndexOf("\"c))
jppintoAuthor Commented:
Thanks jpaulino. Simple & working fine!
Mike TomlinsonMiddle School Assistant TeacherCommented:
I like both approaches...  =)

Here is another one to get the "root" node using GuitarRich's approach:
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim tn As TreeNode = TreeView1.SelectedNode
        If Not IsNothing(tn) Then '
            Dim root As TreeNode = GetRootNode(tn)
            Debug.Print("Root: " & root.Text)
        End If
    End Sub
    Private Function GetRootNode(ByVal tn As TreeNode) As TreeNode
        While Not IsNothing(tn)
            If Not IsNothing(tn.Parent) Then
                tn = tn.Parent
                Return tn
            End If
        End While
        Return Nothing
    End Function
End Class

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now