'Populating a Combobox in a model dialogue in MFC

I am trying to populate a CComboBox in a model dialogue in an MFC application. My data comes from an API and I manage to get that into a JSON array. I need to populate menu items of the CComboBox with name member of the JSON object.

I know how to access it in a for loop. The problem is I don't know how to populate the CComboBoxwith the names I have. I have a a DoDataExchange() function in the .cpp file linked to the dialogue. I tried using the DDX_CBString to populate, but it's only setting the text of combobox with the last name I have and not populating the menu items.

I am very new to the programming world itself, but managed to make some applications some how (basic ones)... I don't know how all these MFC things work... Trying to get a hang of it. If someone could help explaining this simply it will be a great help... Thank you :)



Solution 1:[1]

Say you have a structure:

struct TheData
{
   CString name; 
   // other stuff ...
};

Let's assume your collection is in an array of some sort...

std::vector<TheData> m_theData;

Assume your combo box is m_cbDataStuff and that it was already initialized as a control with a DDX_Control in CYourDerivedDialog::DoDataExchange(CDataExchange* pDX).

You'll want to override OnInitDialog() ...

BOOL CYourDerivedDialog::OnInitDialog()
{
   __super::OnInitDialog();

   for ( size_t idx = 0; idx < m_theData.size(); ++idx)
   {
      int where = m_cbDataStuff.AddString(m_theData.name);
      m_cbDataStuff.SetItemData(where, idx);
   }


   return TRUE;
}

If you aren't sorting, then you don't need to set the index with the call to SetItemData() because the index in the combobox will match the index in the collection. Of course, you could put other things in the item data like an iterator or pointer to the data or whatever. (probably by using SetItemDataPtr() instead)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew Truckle