Pj Carr
Pj Carr

Reputation: 13

Need help comparing a string to a listbox with a loop

Code is below. I'm trying to compare a user input string with a large listbox and if it finds a match, it terminates the loop and prints a response. I keep getting hung up with it freezing or printing the wrong response.

Private Sub btnAction_Click(sender As Object, e As EventArgs) Handles btnAction.Click
        Dim input As String = txtIn.Text
        Dim i As Integer = 0
        While i <= lstRoseBowl.Items.Count - 1
            If input = CStr(lstBox.Items(i)) Then
                txtOut.Text = "Yes"
            Else
                txtOut.Text = "No"
            End If
        End While
    End Sub

Upvotes: 1

Views: 36

Answers (1)

the_lotus
the_lotus

Reputation: 12748

You need to increment "i"

Private Sub btnAction_Click(sender As Object, e As EventArgs) Handles btnAction.Click
        Dim input As String = txtIn.Text
        Dim i As Integer = 0
        While i <= lstRoseBowl.Items.Count - 1
            If input = CStr(lstBox.Items(i)) Then
                txtOut.Text = "Yes"
            Else
                txtOut.Text = "No"
            End If

            i += 1 ' <-----
        End While
    End Sub

Or better yet, use a for loop

Private Sub btnAction_Click(sender As Object, e As EventArgs) Handles btnAction.Click
        Dim input As String = txtIn.Text

        For i As Integer = 0 To lstRoseBowl.Items.Count - 1
            If input = CStr(lstBox.Items(i)) Then
                txtOut.Text = "Yes"
            Else
                txtOut.Text = "No"
            End If
        Next
    End Sub

Now, this will compile and run but might not give you the result you want since if it find the items on the first try, it would then display No on the second try. There are better ways of doing it but for the least amount of code change, it could look like this.

Private Sub btnAction_Click(sender As Object, e As EventArgs) Handles btnAction.Click
        Dim input As String = txtIn.Text

        txtOut.Text = "No"

        For i As Integer = 0 To lstRoseBowl.Items.Count - 1
            If input = CStr(lstBox.Items(i)) Then
                txtOut.Text = "Yes"
                Exit For
            End If
        Next
    End Sub

Upvotes: 3

Related Questions