定义一个自定义控件,控件继承自System.Windows.Forms.ComboBox
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
namespace ComBoxtest
{
public partial class AutoCombobox : System.Windows.Forms.ComboBox
{
public AutoCombobox()
{
InitializeComponent();
}
public AutoCombobox(IContainer container)
{
container.Add(this);
InitializeComponent();
}
protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
AutoComplete((ComboBox)this, e);
base.OnKeyPress(e);
}
public void AutoComplete(ComboBox cb, System.Windows.Forms.KeyPressEventArgs e)
{
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 = false;
}
}
}
}