How to: Determine the Selection in List Web Server Controls
The information in this topic applies to these Web server controls:, , , and .
One of the most common tasks in working with a list Web server control is to determine what item or items users have selected. The procedure varies depending on whether the list control allows single or multiple selections.
Use the following procedure when working with the DropDownList control, the RadioButtonList control, and a single-selection ListBox control.
To determine the selection in a single-selection list control
Use one of the following methods:
To get the index value of the selected item, read the value of theproperty. The index is zero-based. If nothing has been selected, the value of the property is -1.
To get the contents of the selected item, get the control'sproperty. This property returns an object of type . You can get the contents of the selected item by getting the or property of the object.
Controls in a Web Forms page can include potentially malicious client script. By default, the Web Forms page validates that user input does not include script or HTML elements. For more information, see
The following code example shows how you can test which item is selected in a RadioButtonList control. The code first determines whether there is a selection at all by reading the value of theproperty, which is set to -1 until the user selects an item. It then gets the SelectedItem object and displays that object's Text property.
Protected Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ' Is anything selected? The index is -1 if nothing is selected. If RadioButtonList1.SelectedIndex > -1 Then Label1.Text="You chose: " & RadioButtonList1.SelectedItem.Text End If End Sub
If the list control supports multiple selections, you must loop through the control and check for selected items one by one.
To determine the selection in a multi-selection list control
Loop through the control'scollection and test the Selected property of every individual item.
The following code example shows how you can test selections in a multi-selection ListBox control called
ListBox1. The code displays a list of selected items in a label.
Protected Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim msg As String Dim li As ListItem msg = "" For Each li In ListBox1.Items If li.Selected = True Then msg = msg & "<br>" & li.Text & " selected." End If Next Label1.Text = msg End Sub