Working with the ListBox ControlThe ListBox control is similar to the DropDownList control with two important differences. First, the ListBox control requires more screen real estate because it always displays a certain number of list items. Furthermore, unlike the DropDownList control, the ListBox control enables a user to select multiple items. The page in Listing 10.11 illustrates how you can enable a user to select a single item from a ListBox control (see Figure 10.10). Figure 10.10. Displaying list items with the ListBox control.Listing 10.11. ShowListBox.aspx
Notice that the ListBox control in Listing 10.11 includes a Rows property. The Rows property determines the number of list items that the ListBox displays. You can also configure the ListBox control to enable a user to select multiple items. This is illustrated in the page in Listing 10.12 (see Figure 10.11). Figure 10.11. Selecting multiple list items.Listing 10.12. ShowMultipleListBox.aspx
Notice that the ListBox in Listing 10.12 includes a SelectionMode property that is set to the value Multiple. A user can select multiple items from the ListBox by using the Ctrl or Shift key when clicking more than one list item. Warning Most users don't understand how to select multiple items from a ListBox control. If you want to enable users to pick multiple items, a better approach is to use either the CheckBoxList control (discussed in the next section) or the MultiSelectList control (discussed in the final section of this chapter). When you click the Submit button in Listing 10.12, all the selected list items are displayed in a Label control. The SelectedItem, SelectedIndex, and SelectedValue properties return only the first list item selected. When multiple items are selected, you need to iterate through the Items collection of the ListBox control to detect the selected items. |