Controls You Can Use on Web Forms ASP.NET Standard Controls ListBox Control
The information in this topic applies to all list Web server controls: ListBox, DropDownList, CheckBoxList, and RadioButtonList.
Normally, users select items in a list Web server control to indicate their choice. However, you might need to preselect items at design time, or dynamically select items at run time based on some condition.
- Include the Selected attribute in the opening tag of the list item that is to be initially selected.
<asp:ListBox id="myListBox" runat="server">
<asp:ListItem text="Item 1" />
<asp:ListItem text="Item 2" />
<asp:ListItem text="Item 3" selected />
<asp:ListItem text="Item 4" />
<asp:ListItem text="Item 5" />
</asp:ListBox>
- Set the control’s SelectedIndex property to the index value of the item to select. The index is zero-based. To reset ( no selection ), set SelectedIndex to -1.
myList.SelectedIndex = 2; // selects the third item
myList.SelectedIndex = 2 ' selects the third item |
|
C# |
VB |
- Loop through the control’s Items collection and set the Selected property of every individual item.
NOTE: You can only select multiple items in ListBox controls if the control’s SelectionMode property is set to Multiple.
<asp:ListBox id="myList" multiple runat="server">
The following example shows how you can set the selections in a multi-selection ListBox control. In this case, the code selects even-numbered items.
void setSelected ( object src, EventArgs e ) {
int i = 0;
foreach ( ListItem item in myList.Items ) {
if ( i % 2 == 0 ) {
item.Selected = true;
}
i++;
}
}
Sub setSelected ( ByVal src As Object, ByVal e As EventArgs )
Dim i As Integer=0
For Each item As ListItem In myList.Items
If ( i Mod 2=0 ) Then
item.Selected = True
End If
i=i + 1
Next
End Sub |
|
C# |
VB |
Setting Web Forms Server Control Properties Setting Web Server Control Properties Programmatically