Auto Complete ComboBox – C# Windows Forms
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.
1: AutoComplete(ComboBox cb, System.Windows.Forms.KeyPressEventArgs e, bool blnLimitToList)
1: // AutoComplete
2: public void AutoComplete(ComboBox cb, System.Windows.Forms.KeyPressEventArgs e)
3: {
4: this.AutoComplete(cb, e, false);
5: }
6:
7: public void AutoComplete(ComboBox cb, System.Windows.Forms.KeyPressEventArgs e, bool blnLimitToList)
8: {
9: string strFindStr = "";
10:
11: if (e.KeyChar == (char)8)
12: {
13: if (cb.SelectionStart <= 1)
14: {
15: cb.Text = "";
16: return;
17: }
18:
19: if (cb.SelectionLength == 0)
20: strFindStr = cb.Text.Substring(0, cb.Text.Length - 1);
21: else
22: strFindStr = cb.Text.Substring(0, cb.SelectionStart - 1);
23: }
24: else
25: {
26: if (cb.SelectionLength == 0)
27: strFindStr = cb.Text + e.KeyChar;
28: else
29: strFindStr = cb.Text.Substring(0, cb.SelectionStart) + e.KeyChar;
30: }
31:
32: int intIdx = -1;
33:
34: // Search the string in the ComboBox list.
35:
36: intIdx = cb.FindString(strFindStr);
37:
38: if (intIdx != -1)
39: {
40: cb.SelectedText = "";
41: cb.SelectedIndex = intIdx;
42: cb.SelectionStart = strFindStr.Length;
43: cb.SelectionLength = cb.Text.Length;
44: e.Handled = true;
45: }
46: else
47: {
48: e.Handled = blnLimitToList;
49: }
50:
51: }
History
Released on November 8th 2006.
March 25, 2009 - 3:45 am
Thank you!