Search code examples
c#winformsevent-handlingdatetimepickervaluechangelistener

Getting the previous value of an object at ValueChanged event


I am trying to get the previous value of DateTimePicker when it hits the event ValueChanged. The other possible solution to my problem would be getting whether the user clicked on a value and chose it or it was invoked by some method. My problem is I need to know what caused this event and execute some code only if the previous value was different. I have read this and didn't like the solution to the possible way #2.

So again:

if user clicks
{
    execute some code
}
else // if method was invoked
{
    do NOT execute
}

OR

if value is NOT the same as previously
{
    execute some code
}
else
{
    do NOT execute
}

Either of that suits me, but I am unable to find the previous value in the list of available properties nor in EventArgs (which is null :( ). Hope I was clear what I want to achieve. If you ask for the reasons that I need this, it is irrelevant and I cannot edit the other code, just this method.


Solution

  • The ValueChanged-Event, as the name implies, will only be fired when the Value of the DateTimePicker changes. You do not have to check if the value has changed in your code.

    You are stating that you EventArgs is null, but it should be EventArgs.Empty, when used in an unmodified framework.

    If you want to do something else with the LastValue you can use a customized DateTimePicker like this.

    public class LastDateTimePicker : DateTimePicker {
        protected override void OnValueChanged(EventArgs eventargs) {
            base.OnValueChanged(eventargs);
    
            LastValue = Value;
            IsProgrammaticChange = false;
        }
    
        public DateTime? LastValue { get; private set; }
        public bool IsProgrammaticChange { get; private set; }
    
        public new DateTime Value { 
            get { return base.Value; }
            set {
                IsProgrammaticChange = true;
                base.Value = value;
            }
        }
    }
    

    EDIT I have changed my example to met your requirements of checking programmatic changes, as stated in your comment.