Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Combobox (Dropdownstyle = Simple) -- how to select item as you type

Tags:

c#

combobox

I have a Combobox control on my form (WinForms, .NET 3.5), and its DropDownStyle property is set to Simple. Let's say it is populated with the letters of the alphabet, as string objects ("a", "b", "c", and so on).
As I type a letter in the combobox' input field, the correct item will be displayed just underneath.

This is the behaviour I want. But I would also like to have the first matching item selected.

Is there a property of the Combobox control that would achieve that? Or do I need to handle that programatically?

like image 998
Fueled Avatar asked Nov 06 '22 22:11

Fueled


1 Answers

Depending on your needs, you might consider using a TextBox control and setting up the AutoComplete properties (e.g. AutoCompleteMode and AutoCompleteCustomSource)

The difficulty you're going to face is that once you select an item (programatically), the text in the combo box will change. So doing something like this:

private void comboBox1_TextChanged(object sender, EventArgs e)
{
    for(int i=0; i<comboBox1.Items.Count; i++)
    {
        if (comboBox1.Items[i].ToString().StartsWith(comboBox1.Text))
        {
            comboBox1.SelectedIndex = i;
            return;
        }
    }
}

might accomplish what you want (in terms of the selection), but it will also immediately change the user's text.

like image 165
Daniel LeCheminant Avatar answered Nov 12 '22 10:11

Daniel LeCheminant