C# 当列表项以与下拉项相同的文本开头时,如何设置组合框默认值*不在下拉列表中*?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1023323/
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
How do I set a ComboBox default *not in the drop down* when a list item begins with the same text as a drop down item?
提问by John Conrad
Using C#, say you have a ComboBox that has a DropDownStyle set to DropDown (there are items in the drop down but the user can manually enter a value as well). How do you set a default value for the ComboBox that is notin the list of values in the drop down, but begins withtext from a possible selection? Normally setting ComboBox.Text works fine, but if there is an item in the drop down that begins withthe text you want as the default, it automatically selects the first item in the list that starts with the text. For example:
使用 C#,假设您有一个将 DropDownStyle 设置为 DropDown 的 ComboBox(下拉列表中有项目,但用户也可以手动输入一个值)。如何为不在下拉列表中的值列表中的 ComboBox 设置默认值,但以可能选择的文本开头?通常设置 ComboBox.Text 工作正常,但如果下拉列表中有一个以您想要的默认文本开头的项目,它会自动选择列表中以该文本开头的第一个项目。例如:
Values in the drop down:c:\program files\
c:\windows\
d:\media\
下拉列表中的值:c:\program files\
c:\windows\
d:\media\
Default Value AssignmentmyComboBox.Text = "C:\";
默认值分配myComboBox.Text = "C:\";
Result
Initial value of ComboBox when the form opens is "c:\program files\
".
结果
表单打开时 ComboBox 的初始值为“ c:\program files\
”。
So what am I doing wrong? How do I correctly set a default value of an item not in the drop down list that begins with a possible selection?
那么我做错了什么?如何正确设置不在以可能选择开头的下拉列表中的项目的默认值?
采纳答案by JP Alioto
I couldn't repro the behavior you are describing. Adding the three values via the Items collection and then setting the initial value to "c:\" (you omitted an @ in your code sample, by the way) worked fine. My guess is that something else in your code is setting the value of the combo box after you set it.
我无法重现您所描述的行为。通过 Items 集合添加三个值,然后将初始值设置为“c:\”(顺便说一下,您在代码示例中省略了 @)工作正常。我的猜测是您的代码中的其他内容是在您设置组合框后设置它的值。
回答by Jasson
I was able to get this to work with having the items in the ComboBox be ComboBoxItems (I dont see why this wouldn't work with other types). Set the ComboBox.Text like you are and make sure SelectedIndex = -1 and also you need IsEditable = True.
我能够让它与 ComboBox 中的项目成为 ComboBoxItems 一起工作(我不明白为什么这不适用于其他类型)。像您一样设置 ComboBox.Text 并确保 SelectedIndex = -1 并且您还需要 IsEditable = True。
回答by shahkalpesh
Does the following code work?
下面的代码有效吗?
myCombo.SelectedIndex = myCombo.FindString(@"c:\");
Note: I haven't tried it. Looked up for properties/methods that could help using reflector.
注:我没试过。查找有助于使用反射器的属性/方法。