At design time, you can add a list box to a Web form as you can any other
Web server control; just drag one from the toolbox. To add items to a list
box at design time, you can click the Items property in the list
box to open the ListItem Collection Editor you see in Figure
14.4.
Figure 14.4
Adding items to a list box at design time.
Tip - You can make an item appear initially selected
in a list box by setting its Selected property to True (the
default is False) in the ListItem Collection Editor at design
time. |
How do you handle single-selection Web server list boxes in code? When the
user makes a selection by clicking an item in the control, a SelectedIndexChanged event
occurs. Here's how we handle that in the ListBox example, which
displays the currently selected item when the user changes the selection in
the list box:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox1.Text
= "You selected " & ListBox1.SelectedItem.Text
End Sub
You can see the results in Figure
14.3. In single-selection list boxes, you can determine which item is
selected with the list box's SelectedItem property and the
index of the item in the list with the SelectedIndex property.
The ListBox example sets the list box's AutoPostBack property
to True so that its events are handled on the server when they occur.
It's more usual, however, to leave AutoPostBack set to False (the
default) and read what item the user has selected in the list box when the
page is sent back after the user clicks a Submit button. For example, the user
might work with several list boxes, selecting names, dates, colors, and so
on, and then click the Submit button to apply those selections. In the code
that handles the button's click, you can read the current selection in
the various list boxes all at once, something like this:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = ListBox1.SelectedItem.Text & _
" is currently selected in list box 1."
TextBox2.Text = ListBox2.SelectedItem.Text & _
" is currently selected in list box 2."
TextBox3.Text = ListBox3.SelectedItem.Text & _
" is currently selected in list box 3."
End Sub
On the other hand, what if a list box can support multiple selections? Handling more than one selection at a time takes a little more thought.
Comments