Problem with ValueChanged event of DateTimePicker

S

skhairnar

Hi All,
I am trying to write a validation rule for DateTimePicker, which will
prevent user from selecting saturday or sunday as a value. For this I
have added an event handler with following code:

private void dtpStartDate_ValueChanged(object sender, System.EventArgs
e)
{
System.DayOfWeek i = dtpStartDate.Value.DayOfWeek;
if((i == System.DayOfWeek.Sunday) || (i == System.DayOfWeek.Saturday))
{
MessageBox.Show("Please try again, can't select a weekend day");
//Second call to ValueChanged
this.dtpStartDate.Value = DateTime.Today;
}
return;
}

If you see the code flow, the eventhandler should get called 2 times,
first with the date value chosen by then end user and second with
Today's date which I am setting inside my code. No problem here.

But the problem is, the ValueChanged function is getting called again
after completing above two calls. And surprisingly with the same value
that user has choose on the form.

This is the reason, the message box is shown twice to the end user. I
can prevent the message box getting displayed twice by having a flag.
But I am more interested in knowing why the event handler delegate is
behaving incorrectly. Is this a BUG or I am doing anything wrong?
 
S

skhairnar

Got the solution :)...........
declare a form member as below:
private DateTime m_CurrentDate;

and here is the modified ValueChanged:
private void dtpStartDate_ValueChanged(object sender, System.EventArgs
e)
{
bool bComp = false;
System.DayOfWeek i = this.dtpStartDate.Value.DayOfWeek;
if((i == System.DayOfWeek.Sunday) || (i == System.DayOfWeek.Saturday))
{
DateTime dt = ((DateTimePicker)sender).Value;
if((dt.Day == this.m_CurrentDate.Day) && (dt.Month ==
this.m_CurrentDate.Month) && (dt.Year == this.m_CurrentDate.Year))
bComp = true;

if(bComp == false)
{
this.m_CurrentDate = ((DateTimePicker)sender).Value;
MessageBox.Show("Can't select a weekend day, date will be reset to
today's date.");
}
this.dtpStartDate.Value = DateTime.Today;
}
return;
}


Regards,
-Sac
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top