Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/MFC Error accessing control's variable

Tags:

c++

mfc

I created a control's variable for CEdit:

class CGateDlg : public CDialog
{
    ...
    public:
        // here is my control's variable
        CEdit m_edit_a;
        // here I map variable to control
        virtual void DoDataExchange(CDataExchange* pDX);
}

And this is how I map my variable to the control:

void CGateDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_EDIT_A, m_edit_a);
}

This is how it works: user types some text into the edit box. Then he presses the "Reset" button which clears the edit box. This is a piece of code responsible for clearing edit box after clicking Reset button:

void CGateDlg::OnBnClickedReset()
{
    // clear edit box 
    m_edit_a.SetWindowTextW(L"");
}

Application starts without any errors. I type some text into EditBox and hit "Reset" button. Then I get an error which leads me to winocc.cpp, line 245 (ENSURE(this)):

void CWnd::SetWindowText(LPCTSTR lpszString)
{
    ENSURE(this);
    ENSURE(::IsWindow(m_hWnd) || (m_pCtrlSite != NULL));

    if (m_pCtrlSite == NULL)
            ::SetWindowText(m_hWnd, lpszString);
    else
            m_pCtrlSite->SetWindowText(lpszString);
}

I think the problem is with the hWnd:

this    0x0030fa54 {CEdit hWnd=0x00000000}  CWnd * const

but how to fix it ?

Everything works fine when I access my control's value using this:

CEdit *m_edit_a;
m_edit_a = reinterpret_cast<CEdit *>(GetDlgItem(IDC_EDIT_A));
m_edit_a->SetWindowTextW(L"");

What am I doing wrong ?

like image 228
Kamil N. Avatar asked Dec 27 '22 07:12

Kamil N.


1 Answers

I can see two possibilities:

  1. The control does not exist when the dialog starts. The first thing that CDialog::OnInitDialog will do is call DoDataExchange, so if you're creating the control later in the initialization process it's too late.

  2. Your own OnInitDialog is not calling CDialog::OnInitDialog so DoDataExchange is not being called.

like image 200
Mark Ransom Avatar answered Jan 11 '23 05:01

Mark Ransom