This article guide to to create a combobox that can search and has suggest list.
More often than not, when there are so many items in the combobox, adding search feature and a suggest list maybe a good enhancement.
The most basic way to do search in combobox is utilize Autocomplete feature, but it exhibits only string.StartWith() search and there is no way to override that, so to make the combobox search in anywhere you like, with suggest list like Autocomplete do, we need another way out.
Using the code
We will use a listbox to simulate the suggest list of Autocomplete. Firstly, we add a listbox right below the combobox (using the Location property in Property panel maybe easier to do that):
Then we want the combobox do the search everytime we type something in, so we handle the TextChanged event of the combobox (TextUpdated is fine, too):
private void comboBox1_TextChanged(object sender, EventArgs e)
string textToSearch = comboBox1.Text.ToLower();
listBox1.Visible = false; if (String.IsNullOrEmpty(textToSearch))
return; string result = (from i in collections
if (result.Length == 0)
listBox1.Visible = true; }
After that, when we type in the combobox, the listbox shows with the search results (note that the search is case insensitive):
Then we want when user click on an item in the suggest list, the list disappears and the item is displayed on the combobox; we will handle listbox's SelectedIndexChanged event:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
comboBox1.SelectedItem = listBox1.SelectedItem;
listBox1.Visible = false;
Here the combobox displays the same item type as the listbox so the code is short (you should have handled combobox's SelectedIndexChanged event).
There you go, a combobox with searching and suggest list as you type!
Points of Interest
The main idea of using the listbox as the suggest list can be expanded in a broader context, such as textbox with custom autocomplete or a search box that suggests items by images .