Hi, I have a DateTimePicker on one of my forms and when the user change the date I have some code in the _ValueChanged event handler.
Part of the code has a Confirm MessageBox that allows the user to confirm whether he wants to change the date or not. If the user selects no then I change the date back to the original...
Code
...resetDate = true;
dtpExpVector.Value = prevDate;
resetDate = false;
...
I deal with the new _ValueChanged event fired by dtpExpVector.Value = prevDate using the booleans above.
My problem is that for some reason the _ValueChagned event appears to be getting fired an extra time at the end with the date the user selected. Does anybody know why?
It appears to be the line dtpExpVector.Value = prevDate; that is causing the extra event to be fired. I expect it to fire 1 event but it actually seems to fire 2.
For example if the DateTimePicker shows 22nd March and I change it to 9th March I get the following events:
Event 1: _ValueChanged(9th March)
If the user then rejects the change the line dtpExpVector.value = prevDate; is called so:
Event 2: _ValueChanged(22nd March).
This is what I expect but a 3rd Event gets called:
Event 3: _ValueChanged(9th March).
It is this 3rd event that I can't explain.
Thanks.
Wallace
Scott LyslePosted Mar 24, 2007, 1:41 PM
If I understand everything correctly this approach may work for you:
First, set two variables with form wide scope, one for your previous date and one Boolean, in the constructor, set the default value for the previous date to DateTime.Now (or whatever you want it to be), and set the bChangeTime boolean to false.
DateTime dtpPreviousTime;
bool bChangeTime;
public Form1()
{
InitializeComponent();
dtpPreviousTime = DateTime.Now;
bChangeTime = false;
}
Second, write a handler for the CloseUp event for the date time picker control (not the value changed event handler); use the previous date value and the boolean to determine how to respond to the event after collecting the message box confirmation:
private
void dateTimePicker1_CloseUp(object sender, EventArgs e){
if (bChangeTime == false)
{
DialogResult dr = MessageBox.Show("Change the value?", "Date",
MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
bChangeTime = true;
dtpPreviousTime = dateTimePicker1.Value;
bChangeTime = false;
return;
}
else
{
bChangeTime = true;
dateTimePicker1.Value = dtpPreviousTime;
bChangeTime = false;
return;
}
}
}
I tried this out and it worked fine for confirming whether or not to allow the date to update in response to the message box based confirmation. If you use the value changed event handler, when the value changes it calls the value changed event handler again (thus the problem with two confirmations). This approach skips that and denies the value change if the user indicates No to the message box confirmation.