Using Control Members

By Ken Pugh, ITworld |  How-to

There are a couple of differences between
setting the control text directly and using a value member that
corresponds to the control.

First, using ClassWizard, you can set up some simple validation for a
value member (such as a low and high value or the length of a string).
Second, the values of the members and the values inside the controls do
not automatically correspond with each other. If you change the value
of a variable that represent a control, then you'll need to notify the
dialog that you have made those changes.

The UpdateData() function is used to move the member variable values
into the controls. You call UpdateData(FALSE) to set values in the
controls from class members. You call UpdateData(TRUE) to set the class
members from the values in the controls. The use of a boolean, rather
than having two separate functions (e.g. UpdateDataFromControls() and
UpdateControlsFromData()) is sometimes confusing, but unfortunately
that's the interface MFC uses.

The DoDataExchange function is what is called by UpdateData(). You
should never call this yourself. For example, if you use ClassWizard to
set up a variable of type int for the edit box, it will look like:

void CSetWinner::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CSetWinner)
DDX_Control(pDX, IDC_WINNING_VALUE, m_winning_value_ctl);
DDX_Text(pDX, IDC_WINNING_VALUE, CSetWinner::);
//}}AFX_DATA_MAP
}

If you set up simple validation with ClassWizard, you won't need the
validation in the OnOK() function. It can look like:

void CSetWinner::OnOK()
{
CDialog::OnOK();
}

For example, if you set up a min and max value for m_winning_value,
then the AFX_DATA_MAP in DoDataExchange() will have a line that looks
like:

DDV_MinMaxInt(pDX, m_winning_value, 1, 40);

This validation is performed each time UpdateData() is called. If the
value is out of range, an appropriate message is displayed.

If you don't set up a min and max in ClassWizard, you can still do
validation in OnOK(). You will need to get the values from the
controls with UpdateData(). For example:

void CSetWinner::OnOK()
{
UpdateData(TRUE);
if (m_play_value < 1 || m_play_value > 40)
{
AfxMessageBox("Value out of range");
}
else
CDialog::OnOK();
}

If you set up both this validation and the one with ClassWizard, you'll
get two error messages for the same error.

Try using a control member for the edit box in the SetWinner dialog and
a value member for the edit box in the PlayGame dialog and examine the
differences.

In the next column, we'll continue our look at the control classes.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question