Users Pricing

blog

home / developersection / blogs / auto complete combobox in c#

Auto Complete Combobox in C#

Uttam Misra 16217 08 Jan 2011 Updated 18 Sep 2014

This code is written in ComboBox KeyUp event as we have tocheck after every new character is typed. 

private void comboBox1_KeyUp(objectsender, KeyEventArgs e)
        {
            intindex;
            stringactual;
            stringfound;
 
            // Donothing for certain keys, such as navigation keys.
            if((e.KeyCode == Keys.Back) ||
            (e.KeyCode == Keys.Left) ||
            (e.KeyCode == Keys.Right) ||
            (e.KeyCode == Keys.Up) ||
            (e.KeyCode == Keys.Down) ||
            (e.KeyCode == Keys.Delete) ||
            (e.KeyCode == Keys.PageUp) ||
            (e.KeyCode == Keys.PageDown) ||
            (e.KeyCode == Keys.Home) ||
            (e.KeyCode == Keys.End))
            {
                return;
            }
 
            // Storethe actual text that has been typed.
            actual = this.comboBox1.Text;
 
            // Findthe first match for the typed value.
            index = this.comboBox1.FindString(actual);
 
            // Getthe text of the first match.
            if(index > -1)
            {
                found = this.comboBox1.Items[index].ToString();
 
                //Select this item from the list.
                this.comboBox1.SelectedIndex= index;
 
                //Select the portion of the text that was automatically
                //added so that additional typing replaces it.
                this.comboBox1.SelectionStart= actual.Length;
                this.comboBox1.SelectionLength= found.Length;
            }
        }

Uttam Misra

Information Technology

More than 18 years of working experience in IT sector. We are here to serve you best.