articles

Home / DeveloperSection / Articles / Auto complete text in Combo Box

Auto complete text in Combo Box

Anonymous User5558 30-Jul-2010

Here we are going to create AutoComplete ComboBox and we are showing you how to create it.

First of all what is AutoComplete, suppose ComboBox contains more than 200 records and user will have to scroll down or he should write full name but if ComboBox is AutoComplete then it will pick the name instantly.Like ComboBox contains name of the user “Peterson”, when user will type name “pet” then it will pick full name “Peterson” , here below We are going to show you in screenshot so you will understand in better way.

Screen shot

 Auto complete text in Combo BoxAuto complete text in Combo Box

Here is the code

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

 

privatevoid comboBox1_KeyUp(object sender, KeyEventArgs e)
        {
            int index;
            string actual;
            string found;
 
            // Do nothing 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;
            }
 
            // Store the actual text that has been typed.
            actual = this.comboBox1.Text;
 
            // Find the first match for the typed value.
            index = this.comboBox1.FindString(actual);
 
            // Get the 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;
            }
        }
 

Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By