Question

I've added a combo box in the gui editor in MSVC 2010 pro in my MFC project. I have a list of strings I am grabbing from an external source and want to add them to my combo box. I've searched for a while, and every post seems to suggest I need to use the CComboBox class, however, I have no idea how to get the class variable from the resource ID of the combobox element in the gui editor.

In summary, how do I add a string to my combo box, either using a macro (like CB_ADDSTRING(RESOURCE_ID, "my string");) or using CComboBOx (something like CComboBox::GetObject(RESOURCE_ID)->AddString("blah");).

I do not do much win32 api/mfc programming, and just started fiddling around with it.

Was it helpful?

Solution

satuon's answer is the win32 way of doing things. If you want to go a more MFC route then read on.

If there are only a few, you can add your strings directly in the resource editor using the "Data" property of the combo.

If not, then you need to get hold of your combo at runtime. The resource editor will have given you combo a resource id (eg IDC_COMBO1), so you can use that to grab the combo from within your dialog class:

BOOL CcombotestDlg::OnInitDialog()
{
    CDialog::OnInitDialog();

    ((CComboBox*)GetDlgItem(IDC_COMBO1))->AddString("MyString");
}

Note you have to cast to CComboBox, because GetDlgItem() can be used to get any kind of child control.

If you are going to be using the combo a lot, it is probably worth adding a dedicated member to your dialog class. You can do this using the Visual Studio wizard.

  • Right click on your combo.
  • "Add Variable"
  • Give your variable a name, eg "m_MyCombo"
  • Finish

If you now look in your .h file, you will see a new member:

CComboBox m_myCombo;

MFC wires this up for you in DoDataExchange() so you don't need to worry about it. You can now use this member anywhere to manipulate you combo. eg.

BOOL CcombotestDlg::OnInitDialog()
{
    CDialog::OnInitDialog();

    m_MyCombo.AddString("MyString");
}

OTHER TIPS

If you only need it in one spot you can use a temporary pointer:

CComboBox * pComboBox = (CComboBox *) GetDlgItem(nComboBoxID);

Otherwise you can use the wizard to add a class variable which will be mapped to the control during DoDataExchange as the dialog is created.

You can use SendDlgItemMessage:

SendDlgItemMessage(hWnd, nComboBoxID, CB_ADDSTRING, 0, (LPARAM) (LPCTSTR) strText)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top