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?
Add a handler to the KeyChar event (the listbox is named lbxFieldNames in my case):
private void lbxFieldNames_KeyPress(object sender, KeyPressEventArgs e)
{
IncrementalSearch(e.KeyChar);
e.Handled = true;
}
(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:
private void IncrementalSearch(char ch)
{
if (DateTime.Now - lastKeyPressTime > new TimeSpan(0, 0, 1))
searchString = ch.ToString();
else
searchString += ch;
lastKeyPressTime = DateTime.Now;
var item = lbxFieldNames
.Items
.Cast<string>()
.Where(it => it.StartsWith(searchString, true, CultureInfo.InvariantCulture))
.FirstOrDefault();
if (item == null)
return;
var index = lbxFieldNames.Items.IndexOf(item);
if (index < 0)
return;
lbxFieldNames.SelectedIndex = index;
}
The timeout I implemented is one second, but you can change it by modifying the TimeSpan
in the if
statement.
Finally, you will need to declare
private string searchString;
private DateTime lastKeyPressTime;
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):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With