search a list box

juster21

Member
Joined
Oct 1, 2008
Messages
9
Programming Experience
1-3
I want to be able to allow my users to type in a text box and have that text be the 'filter' for a list box.

Here's the situation...if you click on the list box and type S it will jump to the part of the list where the S items are. But if you type SA it returns to the A items. So I'm thinking about using a text box to allow the users to enter their text and search the list box.

I am open to any suggestions!! thanks!!!
 
Not sure why you would want it to return to the 'A' with the typing of the second character of 'SA' instead of moving the index to items starting with 'SA'. Otherwise you might as well just limit it to one letter searches.

Also do you realize that you can use a combobox and set it's DropDownStyle property to Simple and it will appear as a list box with a connected textbox on top of it. It also has AutoCompleteMode & AutoCompleteSource properties built right in that can be set to filter the items as someone types in the text area.
 
What I did was I added a ListBox and a TextBox to a new form and used this code:
VB.NET:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ListBox1.Items.AddRange(New String() {"AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"})
    End Sub

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        If TextBox1.Text.Trim.Length > 0I Then
            ListBox1.SelectedIndex = ListBox1.Items.IndexOf(TextBox1.Text.Trim.ToUpper)
        Else
            ListBox1.SelectedIndex = -1I
        End If
    End Sub
It's not as elegant as it could be, but it gets the point across.
 
'assuming that you have already set your listbox's datasource to bsnames

private sub txt1.textchanged()

if txt1.text = "" then
bsnames.removefilter()
else
bsnames.filter = "Names='" & txt1.text & "'"
end if

end sub
 
Since the listbox is databound you can use the Listbox1.FindString method instead of IndexOf to return the items index or else filter by searching your datasource datatable for the proper record index.

Again I'm not sure why you wouldnt want to use a combobox set to simple which would look the same and have all these methods built-in for you unless you need to use a property/method that the listbox has that the combobox does not.
 
Back
Top