Setting selection by text in CComboBox (MFC)

半腔热情 提交于 2020-01-13 11:26:31

问题


I have a CComboBox of type DropList (i.e. it's not editable). 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.


回答1:


What about 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




回答2:


You can call FindStringExact() to obtain the index of the string you want to select, then pass that index to 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. 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. 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.



来源:https://stackoverflow.com/questions/32867099/setting-selection-by-text-in-ccombobox-mfc

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