Not logged in - Login

Hack to force DateTime control to get proper value in Validating event

In Visual Studio 2010, the DateTimePicker control sometimes does not have the proper value in its Value property during the Validating event.

To recreate-

  • use the mouse to select the month or date portion of the date control.
  • use the numbers on the keyboard (above the letters, not the keypad) to change the value to a single digit value.
  • press the 'Tab' key
  • Inside the Validating event, the value property will contain the previous date value.

To fix, use the following hack: Add an event trap for the Leave event, typically inside the *.designer.cs file. Or, via the GUI.

this.dtRequestedShipDate.Leave += new System.EventHandler(this.dtRequestedShipDate_Leave);

Add the following method to run when the Leave event is fired.

//private bool m_IsSendingKeys = false; // uncomment the references to this if other events need to know not to run during this event.
private void dtRequestedShipDate_Leave(object sender, EventArgs e)
{
  try
  {
    #region Hack to get the value to be correct in the Validating event

    DateTimePicker dtp = sender as DateTimePicker;
    if (dtp != null && !string.IsNullOrEmpty(dtp.Text))
    {
      try
      {
        //this.m_IsSendingKeys = true;
        SendKeys.SendWait("{RIGHT}");
        SendKeys.SendWait("{LEFT}");
      }
      finally
      {
        //this.m_IsSendingKeys = false;
      }
    }

    #endregion
  }
  catch (Exception ex)
  {
    EventHelper.WriteEvent(ex, 1, 1);
  }
}

After the hack is implemented, this Value property of the control will have the correct value inside of the Validating event.

private void dtReqShipDate_Validating(object sender, CancelEventArgs e)
{
  this.lblValidateValue.Text = this.dtReqShipDate.Value.ToString("M/d/yyyy");
}