SelectedItem Property Example

This example adds several Node objects to a TreeView control. After you select a Node, click the form to see various properties of the Node. To try the example, place a TreeView control on a form and paste the code into the form's Declarations section. Run the example, select a Node, and click the form.

Private Sub Form_Load()
   Dim nodX As Node
   Set nodX = TreeView1.Nodes.Add(, , "r", "Root")
   Set nodX = TreeView1.Nodes.Add("r", tvwChild, "c1", "Child 1")
   Set nodX = TreeView1.Nodes.Add("r", tvwChild, "c2", "Child 2")
   Set nodX = TreeView1.Nodes.Add("r", tvwChild, "c3", "Child 3")
   Set nodX = TreeView1.Nodes.Add("c3", tvwChild, "c4", "Child 4")
   Set nodX = TreeView1.Nodes.Add("c3", tvwChild, "c5", "Child 5")
   Set nodX = TreeView1.Nodes.Add("c5", tvwChild, "c6", "Child 6")
   Set nodX = TreeView1.Nodes.Add("c5", tvwChild, "c7", "Child 7")
   nodX.EnsureVisible
   TreeView1.BorderStyle = vbFixedSingle
End Sub

Private Sub Form_Click()
   Dim nodX As Node
   ' Set the variable to the SelectedItem.
   Set nodX = TreeView1.SelectedItem
   Dim strProps As String
   ' Retrieve properties of the node.
   strProps = "Text: " & nodX.Text & vbLF
   strProps = strProps & "Key: " & nodX.Key & vbLF
   On Error Resume Next ' Root node doesn't have a parent.
   strProps = strProps & "Parent: " & nodX.Parent.Text & vbLF
   strProps = strProps & "FirstSibling: " & _
   nodX.FirstSibling.Text & vbLF
   strProps = strProps & "LastSibling: " & _
   nodX.LastSibling.Text & vbLF
   strProps = strProps & "Next: " & nodX.Next.Text & vbLF
   
   MsgBox strProps
End Sub