Selected Property Example

This example adds several Node objects to a TreeView control. When a Node is selected, a reference to the selected Node is used to display its key. 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   ' Create a tree.
   Set nodX = TreeView1.Nodes.Add(,,"r","Root")
   Set nodX = TreeView1.Nodes.Add(,,"p","Parent")
   Set nodX = TreeView1.Nodes.Add("p",tvwChild,,"Child 1")
   nodX.EnsureVisible   ' Show all nodes.
   Set nodX = TreeView1.Nodes.Add("r",tvwChild,"C2","Child 2")
   Set nodX = TreeView1.Nodes.Add("C2",tvwChild,"C3","Child 3")
   Set nodX = TreeView1.Nodes.Add("C3",tvwChild,,"Child 4")
   Set nodX = TreeView1.Nodes.Add("C3",tvwChild,,"Child 5")
   nodX.EnsureVisible   ' Show all nodes.
End Sub

Private Sub Form_Click()
   Dim intX As Integer
   On Error Resume Next   ' If an integer isn't entered.
   intX = InputBox("Check Node",,TreeView1.SelectedItem.Index)
   If IsNumeric(intX) Then   ' Ensure an integer was entered.
      If TreeView1.Nodes(intX).Selected = True Then
         MsgBox TreeView1.Nodes(intX).Text & " is selected."
      Else
         MsgBox "Not selected"
      End If
   End If
End Sub

The following example adds three ListItem objects to a ListView control. When you click the form, the code uses the Selected property to determine if a specific ListItem object is selected. To try the example, place a ListView control on a form and paste the code into the form's Declarations section. Run the example, select a ListItem, and click the form.

Private Sub Form_Load()
   Listview1.BorderStyle = vbFixedSingle  ' Show the border.
   Dim itmX As ListViewItem
   Set itmX = ListView1.ListItems.Add(,,"Item 1")
   Set itmX = ListView1.ListItems.Add(,,"Item 2")
   Set itmX = ListView1.ListItems.Add(,,"Item 3")
End Sub

Private Sub Form_Click()
   Dim intX As Integer
   On Error Resume Next ' If an integer isn't entered.
   intX = InputBox("Check Item", , Listview1.SelectedItem.Index)
   If IsNumeric(intX) Then   ' Ensure an integer was entered.
      If ListView1.ListItems(intX).Selected = True Then
         MsgBox ListView1.ListItems(intX).Text & " is selected."
      Else
         MsgBox "Not selected"
      End If
   End If
End Sub