Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 655
  • Last Modified:

TreeView Top Node name

Hello,

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")?

Thanks,

jppintp
0
jppinto
Asked:
jppinto
1 Solution
 
Éric MoreauSenior .Net ConsultantCommented:
can you show your code?
0
 
GuitarRichCommented:
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
        Else
            ' 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

0
 
jpaulinoCommented:

You can do this:

Dim result As String = Me.Treeview1.SelectedNode.FullPath.Substring(0, Me.Treeview1.SelectedNode.FullPath.IndexOf("\"c))
0
 
jppintoAuthor Commented:
Thanks jpaulino. Simple & working fine!
0
 
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
            Else
                Return tn
            End If
        End While
        Return Nothing
    End Function
 
End Class

Open in new window

0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

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