Catching when user selects an item from a CComboBox

Lou picture Lou · Mar 30, 2009 · Viewed 13.3k times · Source

This is as basic as it gets.

I want to catch when the user selects an item from a CComboBox (actually, a subclass of CComboBox).

Tried lots of combinations of OnCblSelChange, OnCommand. Guess I haven't hit the right combo yet (no pun intended).

OS is Vista but I'm forcing an XP-style dialog (That shouldn't matter, should it?)

I'm able to catch events for classes derived from CEdit and CFileDialog.

I am at my wits end here. Any assistance would be ever-so appreciated.

Any source code would, of course, be more than ever-so appreciated.

Answer

Smashery picture Smashery · Nov 4, 2009

Unfortunately, it seems that all messages (even SELEND_OK) for combo box changing are sent before the text has actually changed, so DoDataExchange will give you the previous text in the CComboBox. I have used the following method, as suggested by MSDN:

void MyDialog::DoDataExchange(CDataExchange* pDX)
{
    DDX_Text(pDX, IDC_COMBO_LOCATION, m_sLocation);
    CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(MyDialog, CDialog)
    ON_CBN_SELENDOK(IDC_COMBO1, &MyDialog::OnComboChanged)
    ON_CBN_EDITUPDATE(IDC_COMBO1, &MyDialog::OnComboEdited) // This one updates immediately
END_MESSAGE_MAP()

...

void MyDialog::OnComboChanged()
{
    m_myCombo.GetLBText(m_myCombo.GetCurSel(), m_sSomeString);
}

void MyDialog::OnComboEdited()
{
    UpdateData();
}

It seems to work quite nicely.