Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Auto Complete ComboBox

4.50/5 (26 votes)
8 Nov 2006CPOL 1   13.1K  
An article on an auto-complete combobox.

Sample Image - AutoCompleteComboBox.gif

Introduction

This is a simple code snippet which is used to make an Auto Complete ComboBox.

Using the code

Usage: Call the function AutoComplete from within the ComboBox's KeyPress event handler.

VB
AutoComplete(ComboBox cb, System.Windows.Forms.KeyPressEventArgs e, bool blnLimitToList)

// AutoComplete
public void AutoComplete(ComboBox cb, System.Windows.Forms.KeyPressEventArgs e)
{
    this.AutoComplete(cb, e, false);
}

public void AutoComplete(ComboBox cb, 
       System.Windows.Forms.KeyPressEventArgs e, bool blnLimitToList)
{
    string strFindStr = "";

    if (e.KeyChar == (char)8) 
    {
        if (cb.SelectionStart <= 1) 
        {
            cb.Text = "";
            return;
        }

        if (cb.SelectionLength == 0)
            strFindStr = cb.Text.Substring(0, cb.Text.Length - 1);
        else 
            strFindStr = cb.Text.Substring(0, cb.SelectionStart - 1);
    }
    else 
    {
        if (cb.SelectionLength == 0)
            strFindStr = cb.Text + e.KeyChar;
        else
            strFindStr = cb.Text.Substring(0, cb.SelectionStart) + e.KeyChar;
    }

    int intIdx = -1;

    // Search the string in the ComboBox list.

    intIdx = cb.FindString(strFindStr);

    if (intIdx != -1)
    {
        cb.SelectedText = "";
        cb.SelectedIndex = intIdx;
        cb.SelectionStart = strFindStr.Length;
        cb.SelectionLength = cb.Text.Length;
        e.Handled = true;
    }
    else
    {
        e.Handled = blnLimitToList;
    }
}

History

  • Released on November 8, 2006.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)