简体   繁体   中英

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

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?

Depending on your needs, you might consider using a TextBox control and setting up the AutoComplete properties (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM