AutoComplete Combo Box

The following code shows how one can autocomplete a combo box in c#.

USAGE: IN THE KEYUP Event of the Combobox on the form just place this code in it

private void ComboBox1_KeyUp(Object sender,System.Windows.Forms.KeyEventArgs e)
}

AutoCompleteCombo(ComboBox1,e);
}
public static void AutoCompleteCombo(ComboBox cbo,KeyEventArgs e)

{

String sTypedText;

Int32 iFoundIndex;

Object oFoundItem;

String sFoundText ;

String sAppendText ;

//'Allow select keys without Autocompleting

switch (e.KeyCode)

{

case Keys.Back:

break;

case Keys.Left:

break;

case Keys.Right:

break;

case Keys.Tab:

break;

case Keys.Up:

break;

case Keys.Delete:

break;

case Keys.Down:

break;

}

//'Get the Typed Text and Find it in the list

sTypedText = cbo.Text;

iFoundIndex = cbo.FindString(sTypedText);

//'If we found the Typed Text in the list then Autocomplete

if (iFoundIndex >= 0)

{ //'Get the Item from the list (Return Type depends if Datasource was bound

//' or List Created)

oFoundItem = cbo.Items[iFoundIndex];

//'Use the ListControl.GetItemText to resolve the Name in case the Combo

//' was Data bound

sFoundText = cbo.GetItemText(oFoundItem);

//'Append then found text to the typed text to preserve case

sAppendText = sFoundText.Substring(sTypedText.Length);

cbo.Text = sTypedText.ToString() + sAppendText.ToString();

//'Select the Appended Text

cbo.SelectionStart = sTypedText.Length;

cbo.SelectionLength = sAppendText.Length;

}

}

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!