asp.net.ph

Skip Navigation Links

Setting the Selection in a List Control

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.

To set the selection in a list Web server control at design time

  • 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>

To set a single selection in a list Web server control programmatically

  • 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
  C# VB

To set multiple selections in a list control programmatically

  • 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++;
   }
}
  C# VB
ListBox4.aspx
Run Sample | View Source
See Also

Setting Web Forms Server Control Properties   Setting Web Server Control Properties Programmatically



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note