Link to home
Start Free TrialLog in
Avatar of Rick
Rick

asked on

asp.net - select items in a listbox in code

Is there a way to select items in a listbox without having to loop through the whole list?

     
      For Each item As ListItem In lstBxBrand.Items
            If item.Text = "Dell" Or item.Text = "HP" Or item.Text = "Sony" Then
                item.Selected = True
            End If
        Next


Thank you.

ASKER CERTIFIED SOLUTION
Avatar of ChetOS82
ChetOS82
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial


Public Shared Sub SetSelected(ByVal objControl As ListBox, ByVal val As String)
        Dim oDR As DataRowView
        Dim i As Integer
        For i = 0 To objControl.Items.Count - 1
            If (objControl.Items(i).Value = "Dell") Or (objControl.Items(i).Value = "HP") Or (objControl.Items(i).Value = "Sony") Then
                objControl.Items(i).Selected = True
            End If
        Next
    End Sub

Open in new window

ListItem li = ListBox1.Items.FindByText("Dell"); // also FindByValue
li.Selected = true;
or
ListBox1.Items[5].Selected = true;
or
ListBox1.SelectedIndex = 5;