I want to implement incremental search on a list of key-value pairs, bound to a Listbox.
If I had three values (AAB, AAC, AAD), then a user should be able to select an item in the available list box and type AAC and this item should be highlighted and in focus. It should be also in incremental fashion.
What is the best approach to handle this?
Maybe you could add an event for
TextChanged
on the control where the user is typing is search (i'm guessing aTextBox
). In the event, you could loop through all items to search the one that is the most corresponding to the words typed by the user.If I'm interpreting your question correctly, it seems like you want users to be able to start typing and have suggestions made.
You could use a ComboBox (instead of a ListBox):
I realize this is extremely late... however, having just implemented this, I'll leave it here in the hope that it will help someone.
Add a handler to the KeyChar event (the listbox is named lbxFieldNames in my case):
(Important: you need
e.Handled = true;
because the listbox implements a "go to the first item starting with this char" search by default; it took me a while to figure out why my code was not working.)The IncrementalSearch method is:
The timeout I implemented is one second, but you can change it by modifying the
TimeSpan
in theif
statement.Finally, you will need to declare
Hope this helps.
You can use the
TextChanged
event to fire whenever the user enter a char, and you can also use thelistbox
eventDataSourceChanged
with it to hover a specific item or whatever you want.I will give you an example:
So whenever the user start to enter any char the
getproducts
method executes and fills the list box and by default hover the first item in the list you can handle that also using the listbox eventDataSourceChanged
to do whatever you want to do.There is also another interesting way to do that, which is:
TextBox.AutoCompleteCustomSource
Property:This list can take only
string[]
, so you can get them from your data source then when the text changed of thetextbox
add the similar words from your data source which had been filled into the textbox autocomplete custom source:Add another event
ListBoxSelectedindexchanged
to add the selected text to the text box