Aaron Hurst
Aaron Hurst

Reputation: 121

Find a selected item in a ListBox

Background: I have a list box that allows multiple selections. There is a specific value in my List Box that, if selected, needs a separate code path to be run for it and all other selections go through another path.

Problem: I can't figure out how to correctly write it in VB.NET to make it work the way I imagine it.

Code:

    For Each Item As String In listbox1.SelectedItems
        If listbox1.SelectedItem = myValue Then
           Do this
        Else
           Do that
        End If
    Next

If I make multiple selections on my list the code doesn't work correctly. It only works correctly if myValue is the only selection in listbox1.

Any suggestions?

Upvotes: 0

Views: 15265

Answers (3)

Mihai Radu
Mihai Radu

Reputation: 1

Example: If ListBox1.SelectedItem = ("Km 1795.5 - 1796.3") Then Form78.Show() End If If ListBox1.SelectedItem = ("Km 1796.6 - 1797.4") Then Form79.Show() End If If ListBox1.SelectedItem = ("Km 1798.7 - 1799.0") Then Form80.Show() End If

Upvotes: 0

The Badak
The Badak

Reputation: 2030

try:

For i = listbox1.Items.Count
    If listbox1.Items[i].IsSelected = True Then
       'Do this
    Else
       'Do that
    End If
Next i

Upvotes: 1

Mataniko
Mataniko

Reputation: 2232

Your iteration is wrong, you should use the Item value in your loop:

For Each Item As String In listbox1.SelectedItems
    If Item = myValue Then
       Do this
    Else
       Do that
    End If
Next

A For Each loop basically does the following: (Please excuse any syntax errors, my vb is rusty)

For index As Integer = 0 To listbox1.SelectedItems.Length
    Def Item = listbox1.SelectedItems[index]
Next

Upvotes: 5

Related Questions