Just can't get it with datepicker
validation.
I have datepicker
From and datepicker
To, so I want to prevent the user from doing some kung fu and seting datepicker
From to be bigger than datepicker
To, I've bumped across some questions but couldn't find the answer, so I've tried doing the easiest way I could think of:
Set MaxDate
property for datepicker
from in form_load
event
private void Form1_Load(object sender, EventArgs e)
{
datepickerFrom.MaxDate = datepickerFrom.Value;
}
Then do the same for value_changed
event
private void datepickerFrom_ValueChanged(object sender, EventArgs e)
{
datepickerFrom.MaxDate = datepickerFrom.Value;
}
This was easy and fine, only few lines of code, and I've only needed datepickerFrom_ValueChanged
event, but recently I've tried typing date into datepicker
insted of selecting it, and then all hell broke loose.
So I came to some solution for validation, instead of setting MaxDate
property, I've tried this.
private void dtFrom_ValueChanged(object sender, EventArgs e)
{
DateTime from = datepickerFrom.Value;
DateTime to = datepickerTo.Value;
int year= from.Year > to.Year ? to.Year : from.Year;
int month = from.Month > to.Month ? to.Month : from.Month;
int day = from.Day > to.Day ? to.Day : from.Day;
int hour = from.Hour > to.Hour ? to.Hour : from.Hour;
int minute = from.Minute > to.Minute ? to.Minute : from.Minute;
int second = from.Second > to.Second ? to.Second : from.Second;
//setting datepicker value
datepickerFrom.Value = new DateTime(year, month, day, hour, minute, second);
}
This works fine, but feels like bit of headache, and I have to do this for datepickerTO_ValueChanged
event also, sure I could make one method
and call it two times, but still feels like there is a batter way for this, so any suggestions?
Thank you for your time