pigeonhands
pigeonhands

Reputation: 3414

Check if item is in listbox Visual Basic

dim foo as string = "hello"

check if foo is in listbox1?

if listbox1.items.contains(foo) then

does not work

Upvotes: 1

Views: 9318

Answers (3)

Dev I.A
Dev I.A

Reputation: 643

hi you can try it out,

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim found As String = ""
    Dim foo As String
    foo = "hello"

    For i As Integer = 0 To ListBox1.Items.Count - 1
        If ListBox1.Items(i).ToString = foo Then
            found = (i)
        End If
    Next

    If found = "" Then
        MessageBox.Show("not found your word!!")
    Else
        MessageBox.Show("found hello, word!")
    End If

End Sub

Upvotes: 0

Codemunkeee
Codemunkeee

Reputation: 1613

Dim foo As String
foo = "Hello"
For i As Integer = 0 To ListBox1.Items.Count - 1
    If ListBox1.Items(i).ToString = foo Then
        MsgBox(i)
    End If
Next

i is the index on the listbox where the item was found.

Upvotes: 3

tinstaafl
tinstaafl

Reputation: 6948

If it's not working then "hello" isn't an item in the listbox items collection. Remember that " hello","hello ","Hello", and "hello" are all different strings. Also .Contains will only compare whole items it won't find a substring within an individual item. You'll need a custom sub routine if that's what you want.

Upvotes: 0

Related Questions