Date validation in MFC

2019-08-31 00:49发布

问题:

I have two date-time picker controls for FROM and TO date. I want to limit the TO date starting date to the FROM date.

Example: If FROM date is 4/12/2013 The TO date picker should allow the user to select date only from 4/12/2013 to current date.

The code is as follows in DoDataExchange() method.

 DDX_Text(pDX, IDC_DATETIME_FILTER_FROM, m_daysStartDateVal);
 DDV_MinMaxDateTime(pDX, m_daysStartDateVal,&StartDate,&COleDateTime::GetCurrentTime());
 DDX_Text(pDX, IDC_DATETIME_FILTER_TO, m_daysEndDateVal);
 DDV_MinMaxDateTime(pDX,m_daysEndDateVal,&m_daysStartDateVal.GetTickCount(),&COleDateTime::GeCurrentTime());

Whenever I change the FROM date it is not reflecting the possible dates in TO date picker.

How can i limit it to the starting date of the FROM date?

回答1:

Dialog data validation does not work like that. You can only specified a (static) range, and the routine verifies that your value is within that pre-defined range. You can extended however this mechanism with your own validation routine.

The example function below takes two variables and a range, and makes sure

void AFXAPI DDV_MinMaxDates(
   CDataExchange* pDX,
   COleDateTime& fromValue, COleDateTime& toValue,
   const COleDateTime* refMinRange, const COleDateTime* refMaxRange)
{
  if(fromValue > toValue ||
     fromValue < refMinRange || fromValue > refMaxRange ||
     toValue < refMinRange || toValue > refMaxRange)
  {
     AfxMessageBox(_T("Incorrect interval!"));
     pDX->Fail();
  }
}

You can use it like this:

DDV_MinMaxDates(pDX, m_daysStartDateVal, m_daysEndDateVal, &StartDate,&COleDateTime::GetCurrentTime());


回答2:

If you want the CDateTimeCtrl controls to dynamically change the allowed ranges depending on the current input in both controls, then you can use CDateTimeCtrl::SetRange. To call SetRange every time one of the controls changed, you should handle the DTN_DATETIMECHANGE notification sent to the parent.