|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
How to: Set the Selection in List Web Server Controls (Visual Studio)
The information in this topic applies to these Web server controls:
Normally, users select items in a list Web server control to indicate their choice. However, you might want to pre-select 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
In the Properties window, click the ellipsis button () for theproperty to open the ListItem Collection Editor dialog box.
From the Members list, choose the member to be selected, and then set itsproperty to true.
If the control is set to allow multiple selections, repeat step 2 for each item to select, and then click OK to close the dialog box.
To set a single selection in a list Web server control programmatically
Do one of the following:
Set the control'sproperty to the index value of the item to select. The index is zero-based. To set no selection, set SelectedIndex to -1.
If you set the SelectedIndex property of a DropDownList control to -1, the control resets the value to 0, because the DropDownList control always has a list item selected.
Set the Selected property of an individual item in the list.
To set multiple selections in a list control programmatically
Loop through the control'scollection and set the Selected property of every individual item.
You can only select multiple items if the control'sproperty 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.
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