This documentation is archived and is not being maintained.

Setting the Selection in a List Web Server 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 want to preselect items or select items at run time (programmatically) based on some condition.

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

  1. In Design view, select the control. In the Properties window, click the ellipsis button (dt1bzx2b.vbellipsesbutton(en-us,VS.71).gif) for the Items property to open the Collection Editor dialog box.
  2. From the Members list, choose the member to be selected, and then set its Selected property to true.
  3. If the control is set to allow multiple selection, repeat Step 2 for each item to select, and then choose OK to close the Collection Editor dialog box.

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 set no selection, set SelectedIndex to -1.
    ' Visual Basic
    ListBox1.SelectedIndex = 2
    ' Selects the third item
    // C#
    ListBox1.SelectedIndex = 2;
    // Selects the third item

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 if the control's SelectionMode property is set to Multiple.

    The following example shows how you can set selections in a multi-selection ListBox control called ListBox1. The code selects every other item.

    ' Visual Basic
    Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       Dim i As Integer
       Dim li As ListItem
       For Each li In ListBox1.Items
          i += 1
          If (i Mod 2 = 0) Then
             li.Selected = True
          End If
    End Sub
    // C#
    public void Button1_Click(object sender, System.EventArgs e)
       // Counter
       int i = 0;
       foreach(ListItem li in ListBox1.Items)
          if( (i%2) == 0)
             li.Selected = true; 
          i += 1;

See Also

Setting ASP.NET Server Control Properties | Setting Web Server Control Properties Programmatically | ListBox Class