Wednesday, November 7, 2007

Auto-Complete for Combo Boxes in C#



This is a very simple auto complete logic which is used commonly and I have moved the logic to a Util Class so that the same logic can be applied to all Combo Boxes in the form.

Add the following class to your C# project



using System;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Collections.Generic;
using System.Collections;

namespace Utils
{
class Util
{
public static void comboBox_KeyPress(ComboBox ctrl,
IDictionary<String,Boolean> acf,
object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (int)Keys.Escape)
{
ctrl.SelectedIndex = -1;
ctrl.Text = "";
acf[ctrl.Name] = true;
}
else if (Char.IsControl(e.KeyChar))
{
acf[ctrl.Name] = true;
}
else
{
acf[ctrl.Name] = false;
}

}

public static void comboBox_TextChanged(
ComboBox ctrl,
IDictionary<String,Boolean> acf,
object sender, EventArgs e)
{
if ( ctrl.Text != "" &&
( ! acf.ContainsKey(ctrl.Name) ||
! acf[ctrl.Name]))
{
string matchText = ctrl.Text;
int match = ctrl.FindString(matchText);
if (match != -1)
{
ctrl.SelectedIndex = match;
ctrl.SelectionStart = matchText.Length;
ctrl.SelectionLength = ctrl.Text.Length-
ctrl.SelectionStart;
}
}

}
}
}



Make sure you have the following import statements inside your form code


using System.Collections.Generic;
using Utils;


Then, at the top of your Form Class , add the following declaration..


IDictionary<String, Boolean> acf = new Dictionary<String, Boolean>();


Then for each combo Box for which you want to have auto complete feature,
add event handlers for the KeyPress & TextChanged events

Just paste the following two lines into the KeyPress event handler


base.OnTextChanged(e);
Util.comboBox_KeyPress(comboBoxCtrlName, acf, sender, e);


Just paste the following two lines into the TextChanged event handler


base.OnTextChanged(e);
Util.comboBox_TextChanged(comboBoxCtrlName, acf, sender, e);


Remember to replace the comboBoxCtrlName with the name of the Combo Box