The information in this topic applies to all list Web server controls: ListBox, DropDownList, CheckBoxList, and RadioButtonList.
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.
Note When you data bind a list control (by calling its
DataBind method), the current list selection is lost. You generally do not want to call the
DataBind method on each round trip (that is, in the page initialization without checking for a post-back), because doing so replaces the values in controls. For details, see
Data Binding Multi-Record Web Server Controls.
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 the SelectedIndex property. 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's SelectedItem property. This property returns an object of type ListItem. You can get the contents of the selected item by getting the Text or Value property of the object.
The following example shows how you can test which item is selected in a RadioButtonList control. The code first checks that there is a selection at all by reading the value of the SelectedIndex property, which is set to -1 until the user selects an item. It then gets the SelectedItem object and displays that object's Text property.
' Visual Basic
Private 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
// C#
public void Button1_Click (object sender, System.EventArgs e)
{
// Is anything selected? The index is -1 if nothing is selected.
if (RadioButtonList1.SelectedIndex > -1) {
// The contents of the selection is available in the
// SelectedItem objects, which provides the Text, Value,
// and Selected properties.
Label1.Text="You chose: " + RadioButtonList1.SelectedItem.Text;
}
}
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
See Also
Setting the Selection in a List Web Server Control | ListBox Class