Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
ASP.NET Programming
Web Server Controls
 How to: Set the Selection in List W...
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
ASP.NET 
How to: Set the Selection in List Web Server Controls 

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

  • Set the Selected property of the list item to true. If the control supports multiple selection, you can set Selected property for each item to be selected.

    The following code example shows how to select the first item in a ListBox control.

    <asp:ListBox ID="ListBox1" runat="server">
        <asp:ListItem Selected="True">A</asp:ListItem>
        <asp:ListItem>B</asp:ListItem>
        <asp:ListItem>C</asp:ListItem>
    </asp:ListBox>&nbsp;</div>
    

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
    ' Selects the third item.
    ListBox1.SelectedIndex = 2

    C#
    // Selects the third item.
    ListBox1.SelectedIndex = 2;

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.

    NoteNote

    You can select multiple items only if the control's SelectionMode property is set to Multiple.

    The following code 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
       Next
    End Sub

    C#
    Protected 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

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker