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?

*爱你&永不变心* 提交于 2020-01-03 00:32:33

问题


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 not in the list of values in the drop down, but begins with text from a possible selection? Normally setting ComboBox.Text works fine, but if there is an item in the drop down that begins with the text you want as the default, it automatically selects the first item in the list that starts with the text. For example:

Values in the drop down:
c:\program files\
c:\windows\
d:\media\

Default Value Assignment
myComboBox.Text = "C:\";

Result
Initial value of ComboBox when the form opens is "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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1023323/how-do-i-set-a-combobox-default-not-in-the-drop-down-when-a-list-item-begins-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!