Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DateTimePicker and MaxDate property

Status
Not open for further replies.

LianaT

Programmer
Oct 26, 2005
2
AT
Hi!

I use a DateTimePicker control to display the time. MaxDate is set for example to 2:10 and the control's Value is 1:55. If I select the hour in control and use up-arrow to increase the hour, the control's value is changed to 2:10, which is MaxDate value. But if Value is 1:55 and I try to type 2 instead of 1, the Value is not changed. I'd like to set control's Value to its MaxDate value in this situation too. Could you give me a suggestion how to do this, please?

Mihaela
 
Does it have keypress event or keydown? IN case it has when you type 2 detect it using that event and set the value to maxdate
 
I tried to catch KeyPress, KeyUp, KeyDown events, but the Value property was not the one I typed, but the old value(1:55 in my example). I think that the control catches the event before me and doesn't allow the change. ValueChanged event occurs only when I use the up-arrow to change the hour.
 
I can't help you in C#, however this VB.Net code seems to do what you need

Code:
 Private Sub ValidateTime()

    'make a copy of the default max date/time for later
    Dim maxval As DateTime = DateTimePicker1.MaxDateTime

    'set a temporary max date/time to allow us to process data
    Dim maxdate As String = "31/12/9997"
    Dim targetmax As DateTime = CDate(maxdate + " 2:10")
    DateTimePicker1.MaxDate = CDate(maxdate + " 23:59")

    'process the data
    Dim s As String = DateTimePicker1.Text
    If CDate(maxdate + " " + s) > targetmax Then
      DateTimePicker1.Value = targetmax
    End If

    'restore the original max date/time
    DateTimePicker1.MaxDate = maxval

  End Sub

  Private Sub DateTimePicker1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DateTimePicker1.KeyDown

    ValidateTime()

  End Sub

  Private Sub DateTimePicker1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles DateTimePicker1.LostFocus

    ValidateTime()

  End Sub

For some reason I've found that using either LostFocus or KeyDown doesn't always work, but using them both seems to.

By the way, 31/12/9997 is the maximum date that allows for a time of 23:59


Hope this helps.

[vampire][bat]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top