double trip through an event

G

Guest

I have a DateTimePicker. The user should pick the first of the month. If he
doesn't, the ValueChanged event pops a messagebox and changes the value to
the first. Problem is that changing the Value in the event triggers the event
twice, and the messagebox appears twice, though I don't see why it should.
Any explanation?

private void dtpRenew_ValueChanged(object sender, System.EventArgs e)
{
int day = dtpRenew.Value.Day ;
if(day != 1)
{ MessageBox.Show("Starting Date must be first day of the month!") ;
dtpRenew.Value = dtpRenew.Value.AddDays(1-day) ;
}
}
 
L

Ludwig Stuyck

I have a DateTimePicker. The user should pick the first of the month. If he
doesn't, the ValueChanged event pops a messagebox and changes the value to
the first. Problem is that changing the Value in the event triggers the event
twice, and the messagebox appears twice, though I don't see why it should.
Any explanation?

private void dtpRenew_ValueChanged(object sender, System.EventArgs e)
{
int day = dtpRenew.Value.Day ;
if(day != 1)
{ MessageBox.Show("Starting Date must be first day of the month!") ;
dtpRenew.Value = dtpRenew.Value.AddDays(1-day) ;
}
}

Use BeginInvoke:

private void dateTimePicker1_ValueChanged(object sender,
System.EventArgs e)
{
int day = dateTimePicker1.Value.Day;
if (day != 1)
{
this.BeginInvoke(new
MethodInvoker(ValidateDate));
}
}
private void ValidateDate()
{
int day = dateTimePicker1.Value.Day;
dateTimePicker1.Value =
dateTimePicker1.Value.AddDays(1-day);
MessageBox.Show("Starting Date must be first
day of the month!") ;
}
 
G

Guest

Thanks. Creating a new object also works, and is a bit more compact. I don't
understand why this happens, especially as the example is essentially the
same as an example.

private void dtpRenew_ValueChanged(object sender, System.EventArgs e)
{
DateTime dt = dtpRenew.Value ;
if (dt.Day != 1)
{
MessageBox.Show("Date must be first day of the month!");
dtpRenew = new DateTimePicker() ;
dtpRenew.Value = dt.AddDays(1-dt.Day) ;}
}
 

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