JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Determining Which List Box Items Are Selected

The big point of list boxes is to let the user make selections, of course, and there are a number of properties to handle that process. Here's an overview.

If a list box supports only single selections, you can use the SelectedIndex property to get the index of the selected item, and the SelectedItem property to get the selected item itself. Here's how I can display a selected item's index:

Private Sub ListBox1_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles ListBox1.Click
    TextBox1.Text = ListBox1.SelectedIndex
End Sub

I also can use the SelectedItem property to get the object corresponding to the selected item, and if that object supports a ToString method, I can display it like this:

Private Sub ListBox1_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles ListBox1.Click
    TextBox1.Text = ListBox1.SelectedItem.ToString()
End Sub

You can see an example, ListBoxes on the CD-ROM, where I've selected and reported on an item in Figure 7.7. There's another, even easier, way to get the text of the selected item's text from a list box—just use the list box's Text property, like this:

Private Sub ListBox1_Click(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles ListBox1.Click
    TextBox1.Text = ListBox1.Text
End Sub

Note that list boxes can support multiple selections if you set their MultiSelect property to True, and the story is different for multiselect list boxes. For multiselect list boxes, you use the SelectedItems and SelectedIndices properties to get access to the selected items. For example, here's how I can use a For Each loop to loop over and display the selected items in a multiselect list box using the SelectedItems collection:

For Each Item In ListBox1.SelectedItems
    TextBox1.Text &= Item.ToString()
Next

And here's how I can do the same thing using the SelectedIndices collection, like this:

For Each Index In ListBox1.SelectedIndices
    TextBox2.Text &= ListBox1.Items(Index).ToString()
Next

For more information, see "Creating Multiselect List Boxes" later in this chapter.

Previous Section Next Section




JavaScript Editor Free JavaScript Editor     JavaScript Editor