Question

I have a case where the user is given a ComboBox with potentially a lot of choices in it. Paired with this is a TextBox that filters the items. What I would like to do is open the drop down list when the TextBox has focus--let the user see what the current filter accomplishes as they type it. (This isn't just autocomplete, I'm currently matching the filter text anywhere in the item, I may replace this with a RegEx search down the road.)

It sounds simple enough--drop the box when the TextBox gets focus, close it when it loses focus. It opens--and promptly closes back up. Any good answers?

My Google-Fu must be weak tonight, I can't believe nobody has wanted to do this before yet I find nothing out there. (I have seen a related thing of typing in an open ComboBox to provide suggested options like Google does but my list is required, not merely suggestions.)

Was it helpful?

Solution

You can add on the Focus event of the TextBox code for the ComboBox setting the property

ComboBox.DroppedDown = true;

Than add on the TextChanged event of the TextBox code

ComboBox.SuspentLayout();
//ComboBox.Items add/remove
ComboBox.ResumeLayout();

Don't forget to reset the items when Text is empty.

EDIT:

This seems to work (but you don't get to see the mouse)

string[] items = { "abcd", "abc", "bcd", "cd" };

private void textBox1_TextChanged(object sender, EventArgs e)
{
    comboBox1.SuspendLayout();
    comboBox1.Items.Clear();
    comboBox1.Items.AddRange(items.Where(item => item.ToLower().Contains(textBox1.Text.ToLower())).ToArray());
    comboBox1.ResumeLayout();
    comboBox1.DroppedDown = true;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top