简体   繁体   English

在CComboBox(MFC)中按文本设置选择

[英]Setting selection by text in CComboBox (MFC)

I have a CComboBox of type DropList (ie it's not editable). 我有一个DropList类型的CComboBox(即它不可编辑)。 What's the easiest way to set the current selection by string? 用字符串设置当前选择的最简单方法是什么?

I know I can use SetCurSel() to set it by index, but I want the function to search through the list-items by string and set it. 我知道我可以使用SetCurSel()通过索引设置它,但我希望该函数按字符串搜索列表项并进行设置。

What about CComboBox::SelectString ? CComboBox :: SelectString怎么样?

"Searches for a string in the list box of a combo box, and if the string is found, selects the string in the list box and copies it to the edit control." “在组合框的列表框中搜索字符串,如果找到该字符串,则在列表框中选择该字符串并将其复制到编辑控件。”

https://msdn.microsoft.com/en-us/library/30ft9e54(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/30ft9e54(v=vs.110).aspx

You can call FindStringExact() to obtain the index of the string you want to select, then pass that index to SetCurSel() : 您可以调用FindStringExact()来获取要选择的字符串的索引,然后将该索引传递给SetCurSel()

yourComboBox.SetCurSel(yourComboBox.FindStringExact(0, yourString));

Note that is the string is not found in the combobox, -1 will be passed to SetCurSel() , which will result in any previous selection being cleared. 注意,在组合框中找不到字符串, -1将被传递给SetCurSel() ,这将导致任何先前的选择被清除。 You may want to perform an explicit test if that behavior does not suit you. 如果该行为不适合您,您可能希望执行显式测试。

Note that Max's answer should be preferred for new developments. 请注意, Max的答案应该是新开发的首选。 However, SelectString() is only supported from Windows Server 2003 onwards, so you may not be able to leverage it, depending on the platforms you want to support. 但是,仅从Windows Server 2003开始支持SelectString() ,因此您可能无法利用它,具体取决于您要支持的平台。

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

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