C# Combobox (Dropdownstyle = Simple) -- 如何在键入时选择项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/533923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Combobox (Dropdownstyle = Simple) -- how to select item as you type
提问by Fueled
I have a Combobox control on my form (WinForms, .NET 3.5), and its DropDownStyleproperty is set to Simple. Let's say it is populated with the letters of the alphabet, as stringobjects ("a", "b", "c", and so on).
As I type a letter in the combobox' input field, the correct item will be displayed just underneath.
我的表单(WinForms、.NET 3.5)上有一个 Combobox 控件,它的DropDownStyle属性设置为Simple。假设它用字母表中的字母填充,作为字符串对象(“a”、“b”、“c”等)。
当我在组合框的输入字段中键入一个字母时,正确的项目将显示在下方。
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?
是否有 Combobox 控件的属性可以实现这一点?还是我需要以编程方式处理?
采纳答案by Daniel LeCheminant
Depending on your needs, you might consider using a TextBox control and setting up the AutoComplete properties (e.g. 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.
可能会完成您想要的(在选择方面),但它也会立即更改用户的文本。