Change Control's Value by a Function in MFC?

I Set an int Variable for IDC_EDIT1 Control. now i Want Change it With a Function, But when clicking on Button, Show an Error!

void test()
{
    CthDlg d;
    d.m_text1 = 5;
    d.UpdateData(FALSE);
}

void CthDlg::OnBnClickedOk()
{
    // TODO: Add your control notification handler code here
    // pThread = AfxBeginThread(ThreadFunction, THREAD_PRIORITY_NORMAL);
    test();
}

enter image description here

Upvotes: 0

Views: 548

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409442

In the test function you define a completely new instance of the CthDlg class, and try to modify it. That will not work as it's not properly created, and also have no relation with the actual dialog being displayed.

Instead, if test is a stand-alone (not member) function then you should pass the actual dialog instance as an argument, and use that.

For example

void tesy(CthDlg& dlg)
{
    dlg.m_text1 = ...;
    dlg.UpdateData(FALSE);
}

void CthDlg::OnBnClickedOk()
{
    test(*this);
}

Upvotes: 4

xMRi
xMRi

Reputation: 15375

The controls are created when you call DoModal or Create. And therefore calling UpdateData will only succeed when the Dialog is created.

This is the usual sequence: The value members may be set before you Launch the Control. The data is transferred when the Dialog is created and transfered back from the controls into the data members when the Dialog is closed with OnOK.

Upvotes: 1

Related Questions