-2

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 :)

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
  • 2
    You aren't going to learn MFC by trying to get the hang of it. That hasn't happened to anyone, ever. See [this Q&A](https://stackoverflow.com/q/18165076/1889329) to learn about the absolute minimum required to learn MFC. – IInspectable May 15 '22 at 07:30
  • It is very easy to find an article about the basic functionality of a `CComboBox` in MFC. For example: https://www.tutorialspoint.com/mfc/mfc_combo_boxes.htm. – Andrew Truckle May 16 '22 at 14:58

1 Answers1

2

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)

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Joseph Willcoxson
  • 5,853
  • 1
  • 15
  • 29