Controls You Can Use on Web Forms ASP.NET Standard Controls ListBox Control
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.
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, which in turn provides the Text, Value, and Selected values of the object.
The following example shows how you can test which item is selected in a ListBox control. The code first checks if 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.
void getSelected ( object src, EventArgs e ) {
// is anything selected? index is -1 if none.
if ( myList.SelectedIndex > -1 ) {
Message.Text = "You chose " + myList.SelectedItem.Text;
// ... do something more exciting ...
}
}
Sub getSelected ( ByVal src As Object, ByVal e As EventArgs )
' is anything selected? index is -1 if none.
If myList.SelectedIndex > -1 Then
Message.Text = "You chose " & myList.SelectedItem.Text
' ... do something more exciting ...
End If
End Sub |
|
C# |
VB |
If the list control supports multiple selections, you must loop through the control and check for selected items one by one.
- Loop through the control’s Items collection and test the Selected property of every individual item.
The following example shows how you can test for selections in a multi-selection CheckBoxList control. The code displays a list of selected items in a label.
void getSelected ( object src, EventArgs e ) {
String s = "Selected items:<br>";
foreach ( ListItem item in myList.Items ) {
if ( item.Selected ) {
// list the selected item
s += item.Text + "<br>";
}
}
Message.Text = s;
}
Sub getSelected ( ByVal src As Object, ByVal e As EventArgs )
Dim s As String = "Selected items:<br>"
For Each item As ListItem In myList.Items
If item.Selected Then
' list the selected item
s = s & item.Text + "<br>";
End If
Next
Message.Text = s
End Sub |
|
C# |
VB |
Setting the Selection in a List Control