Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting selection by text in CComboBox (MFC)

Tags:

c++

mfc

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.

like image 368
padraigf Avatar asked Dec 25 '22 13:12

padraigf


2 Answers

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.

like image 177
Frédéric Hamidi Avatar answered Jan 27 '23 08:01

Frédéric Hamidi


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

like image 26
Max Avatar answered Jan 27 '23 08:01

Max