What I want to do, is to search in a ComboBox, for a word, or a part of a word like this:
For example I have these entries in my combobox:
abc
Abc
Dabc
adbdcd
And when I search for "abc
", it should show me every one in the list, except "
adbdcd"
I fill my combobox from a mysql database, so my items are in a "Collection
".
I have autocomplete enabled (mode: SuggestAppend, source: ListItems)
This is the code, I am using right now:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e) { comboKeyPressed(); }
private void comboBox1_TextChanged(object sender, EventArgs e)
{
if (comboBox1.Text.Length == 0) comboKeyPressed();
}
private void comboKeyPressed()
{
comboBox1.DroppedDown = true;
object[] originalList = (object[])comboBox1.Tag;
if (originalList == null)
{
// backup original list
originalList = new object[comboBox1.Items.Count];
comboBox1.Items.CopyTo(originalList, 0);
comboBox1.Tag = originalList;
}
// prepare list of matching items
string s = comboBox1.Text.ToLower();
IEnumerable<object> newList = originalList;
if (s.Length > 0)
{
newList = originalList.Where(item => item.ToString().ToLower().Contains(s));
}
// clear list (loop through it, otherwise the cursor would move to the beginning of the textbox...)
while (comboBox1.Items.Count > 0)
{
comboBox1.Items.RemoveAt(0);
}
// re-set list
comboBox1.Items.AddRange(newList.ToArray());
}
The problem with this code, is if I search for "abc
" in my example list, "adbdcd
" will show up too. And this code randomly crashes my program when I hit backspace in the combobox.