How can I get the value (string) of the current selection in a combobox?
(Not the integer index)
How can I get the value (string) of the current selection in a combobox?
(Not the integer index)
There might be a better way (my MFC is a bit rusty), but it seems like you should be able to call CComboBox::GetLBText()
, passing it the current selection using CComboBox::GetCurSel()
.
A plain old GetWindowText
works, too.
Edit: As ajryan points out, GetWindowText
actually doesn't work in a CBN_SELCHANGE
handler, because the new selection has taken effect but the window text hasn't been updated with the text of the new selection when the WM_COMMAND
is sent.
CComboBox m_CComboBox;
CString currentValue;
m_CComboBox.GetWindowTextA(currentValue);
cout<<"My current Value is: <<currentValue<<endl;
Have to work with MFC in 2022 .....
char buffer[MAX_COMBO_STRING_LENGTH];
int index= static_cast<int>(SendDlgItemMessage(hDlg, ID_COMBO_BOX, CB_GETCURSEL, 0, 0));
SendDlgItemMessage(hDlg, ID_COMBO_BOX, CB_GETLBTEXT, index, (LPARAM)(LPCTSTR)buffer);
//buffer contains the selected text unless CB_GETCURSEL returned CB_ERR (-1) to the index
There are several approaches to this.
When you use a combo you can map it to a variable.
int
.CString
.As others have said, when your combo is a drop down you can think of it as having two the controls (list and edit). Use GetWindowText
To access the edit control text.
There are many helper macros you can use. And there is one for getting the text (ComboBox_GetText
macro). Saves you needing to map control to variable.
It really depends on your needs and usage of the combo control.