I'm running a search query that pulls the search string from one textbox then searches a listbox for the string and displays the results in a second listbox. I would like to define the number of items that it returns based on a second text box. So far I am able to get all list items with the given string to show in the second box. But I have yet to get it to limit the search to 1 item etc. The functioning code I've used to show all results is:

Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click

    lstResults.Items.Clear()
    If txtSearch.Text.Length > 0 Then
        For index As Integer = 0 To lstCountries.Items.Count - 1
            Dim txt = lstCountries.Items(index).ToString()
            If txt.StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase) Then
                lstResults.Items.Add(txt)
            End If
        Next
    End If

I've tried using while txtnumber.text > 1 then ahead of this but seem to have created a loop. Any ideas as to what I'm missing?

I used the following and got it to work!

Dim Max as integer = Convert.Toint32(txtNumber.Text)
Dim Count as integer = 0

lstResults.Items.Clear()

 For index As Integer = 0 To lstCountries.Items.Count - 1

        if lstCountries.Items(index).StartsWith(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase) Then
            lstResults.Items.Add(lstCountries.Items(index))
            count += 1
        end if

        ' exit the loop if we found enough
        If count>= Max Then
            Exit For               
        End If
  Next
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.