Search code examples
c#datetimepicker

C# datetimepicker reading values before changing date


I have a win form in C# which uses a DateTimePicker and few textboxes. The textboxes collect some information from the user specific to the date in the DateTimePicker.

I want to save the data in textboxes when the date is changed in DateTimePicker.

For that I need to read the date in DateTimePicker before the date is changed.

How could I do that? DateTimePicker_valueChanged event doesn't seem to do this.

The value read from the dateTimePicker is the value after changing the date. How could I get the date before changing date?

Please help.


Solution

  • You need to store the value in some sort of variable when you set the value.

    So if you are setting the value on load of a form, then you store it in the variable too. When the change event fires then you can use the stored variable. Once you have finished with it, you can update it to match the new changed value ready for the next time it is changed.

    For example:

    public class MyClass
    {
    
        DateTime? LastDateValue = null;
    
        void OnLoad()
        {
           //Set both datepicker and LastDateValue to be the same
        }
    
        void DateTimePicker_valueChanged()
        {
           //use LastDateValue to save text fields
           //set LastDateValue to match new value ready to use on next event fire
        }
    
    }