using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; public class Form1 : System.Windows.Forms.Form { private AutoCompleteComboBox combo; public Form1() { this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 273); combo = new AutoCompleteComboBox(); combo.Location = new System.Drawing.Point(64, 32); combo.Size = new System.Drawing.Size(150, 20); combo.Items.Add("Aaaaaa"); combo.Items.Add("Bbbbbbbbb"); combo.Items.Add("Ccccccccccc"); Controls.Add(combo); CenterToScreen(); } static void Main() { Application.Run(new Form1()); } } public class AutoCompleteComboBox : System.Windows.Forms.ComboBox { public event System.ComponentModel.CancelEventHandler NotInList; private bool strict = true; private bool isEditing = false; public AutoCompleteComboBox() : base() { } public bool Strict { get { return strict; } set { strict = value; } } protected virtual void OnNotInList(System.ComponentModel.CancelEventArgs e) { if (NotInList != null) { NotInList(this, e); } } protected override void OnTextChanged(System.EventArgs e) { if (isEditing) { string input = Text; int index = this.FindString(input); if (index >= 0) { isEditing = false; SelectedIndex = index; isEditing = true; Select(input.Length, Text.Length); } } base.OnTextChanged(e); } protected override void OnValidating(System.ComponentModel.CancelEventArgs e) { if (this.Strict) { int pos = this.FindStringExact(this.Text); if (pos == -1) { OnNotInList(e); } else { this.SelectedIndex = pos; } } base.OnValidating(e); } protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e) { isEditing = (e.KeyCode != Keys.Back && e.KeyCode != Keys.Delete); base.OnKeyDown(e); } }