简体   繁体   English

C#组合框(Dropdownstyle =简单)—如何在键入时选择项目

[英]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 . 我在窗体(WinForms,.NET 3.5)上有一个Combobox控件,其DropDownStyle属性设置为Simple Let's say it is populated with the letters of the alphabet, as string objects ("a", "b", "c", and so on). 假设它以字符串对象(“ a”,“ b”,“ c”等)填充了字母。
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) 根据您的需要,您可以考虑使用TextBox控件并设置AutoComplete属性(例如AutoCompleteMode和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. 可能会完成您想要的(根据选择),但是它也会立即更改用户的文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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