Finding Out What Is Selected

It's common to want to find out what is currently selected in a ListBox. The SelectedIndex property represents the zero-based index of the item that is currently selected. The value of -1 denotes that nothing is currently selected. SelectedItem returns the value of the currently selected item, so you can retrieve the string associated with an item, like this:

' Get the selected index

Dim ix As Integer = ListBoxl.SelectedIndex ' Display it in a message box

MsgBox("Item selection: index=" + ix.ToString() + _ ", item=" + ListBox1.SelectedItem.ToString() + "'")

Note the use of the ToString() method to convert both the index and the item into strings for display. You can also use SelectedIndex to set the selected item in case you want to display a ListBox with a particular item selected by default. If you don't select an item, nothing will be selected in the ListBox:

' Select the second item

ListBoxl.SelectedIndex = 1

If you are using a multiple-selection control, you need to use two alternative properties, SelectedIndices and SelectedItems, which return collections holding information about the currently selected items. These are standard collection objects that implement ICollection and IEnumerable, so they can be manipulated using any of the techniques discussed in Chapter 4. The following example shows how you can find out how many elements are selected by enumerating over the collection:

' Get the collection of indices

Dim mbIdx As ListBox.SelectedIndexCollection = ListBoxl.SelectedIndices

' How many elements are selected?

MsgBox("Selected " + mbIdx.Count.ToString() + " items")

' Set up an enumerator to iterate over the collection Dim en As IEnumerator = mbSel.GetEnumerator While en.MoveNext = True

Console.WriteLine(en.Current) End While

0 0

Post a comment