65.9K
CodeProject is changing. Read more.
Home

Create combobox with search and suggest list

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (9 votes)

Jun 25, 2014

CPOL

1 min read

viewsIcon

56500

downloadIcon

11

How to make a combobox with search and suggest list

Introduction

This article guide to to create a combobox that can search and has suggest list.

Download ComboboxWithSearching.rar

Background

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)
{
    // get the keyword to search
    string textToSearch = comboBox1.Text.ToLower();
    listBox1.Visible = false; // hide the listbox, see below for why doing that
    if (String.IsNullOrEmpty(textToSearch))
        return; // return with listbox hidden if the keyword is empty
    //search
    string[] result = (from i in collections
            where i.ToLower().Contains(textToSearch)
            select i).ToArray();
    if (result.Length == 0)
        return; // return with listbox hidden if nothing found

    listBox1.Items.Clear(); // remember to Clear before Add
    listBox1.Items.AddRange(result);
    listBox1.Visible = true; // show the listbox again
}

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 :).

History

Version 1.1