The ListBox control allows the user to select either one or multiple items, depending on the setting of the SelectionMode property. In a single-selection ListBox control, you can retrieve the selected item by using the SelectedItem property, and its index by using the SelectedIndex property. SelectedItem returns the selected item, which is an object. The text of the selected item is reported by the Text property.
If the control allows the selection of multiple items, they’re reported with the SelectedItems property. This property is a collection of objects and exposes the same members as the Items collection. Because the ComboBox does not allow the selection of multiple items, it provides only the SelectedIndex and SelectedItem properties.
To iterate through all the selected items in a multiselection ListBox control, use a loop such as the following:
Dim itm As Object For Each itm In ListBox1.SelectedItems Debug.WriteLine(itm) NextCode language: VB.NET (vbnet)
The itm variable should be declared as Object because the items in the ListBox control are objects. If they’re all of the same type, you can convert them to the specific type and then call their methods. If all the items are of the Rectangle type, you can use a loop like the following to print the area of each rectangle:
Dim itm As Rectangle For Each itm In ListBox1.SelectedItems Debug.WriteLine(itm.Width * itm.Height) NextCode language: VB.NET (vbnet)