MFC › 4. Dialogs and Controls
Dialogs and DDX/DDV
Build a modal dialog and exchange data between controls and member variables with DDX/DDV.
intermediate #mfc#cdialog#ddx#ddv#controls
Explanation
A dialog is described in a resource template (.rc) and wrapped by a class derived from CDialog. DDX (Dialog Data Exchange) copies values between controls and member variables; DDV (Dialog Data Validation) checks them. Both run inside DoDataExchange, triggered by UpdateData(TRUE/FALSE).
UpdateData(TRUE): controls → variables (read the user’s input).UpdateData(FALSE): variables → controls (show values).
Example
#include <afxwin.h>
class CLoginDlg : public CDialog {
public:
enum { IDD = IDD_LOGIN };
CString m_user;
int m_age = 0;
explicit CLoginDlg(CWnd* pParent = nullptr) : CDialog(IDD, pParent) {}
protected:
void DoDataExchange(CDataExchange* pDX) override {
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT_USER, m_user); // control <-> variable
DDX_Text(pDX, IDC_EDIT_AGE, m_age);
DDV_MaxChars(pDX, m_user, 20); // validation
DDV_MinMaxInt(pDX, m_age, 0, 120);
}
};
class CMainFrame : public CFrameWnd {
protected:
afx_msg void OnLogin() {
CLoginDlg dlg;
dlg.m_user = _T("guest"); // shown in the edit box when the dialog opens
if (dlg.DoModal() == IDOK) { // OK runs UpdateData(TRUE) + validation first
AfxMessageBox(_T("Hello ") + dlg.m_user);
}
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_COMMAND(ID_FILE_LOGIN, &CMainFrame::OnLogin)
END_MESSAGE_MAP()
Pitfalls
- Reading member variables before
DoModal()returnsIDOKgives stale values. - Controls do not exist until
OnInitDialog; touching them in the constructor crashes. - Validation failure keeps the dialog open and shows a message. This is by design.
- If you override
OnOK, callCDialog::OnOK()(it runsUpdateData(TRUE)and then ends the dialog). CallingEndDialog(IDOK)yourself skips data exchange and validation.
Exercises
1. Which call refreshes the edit boxes after you change m_user in code?
UpdateData(FALSE);