Search code examples
c#.netwinformsstack-overflow

How to prevent StackOverflow error when changing values of two dependent DateTimePickers?


I have the three DateTimePicker, where one of them is the interval between startdate and enddate. In a part of the code, I update startdate.Value and enddate.Value, whose ValueChanged events update interval.Value.

DateTimePickers

Everything works fine when the value in interval doesn't need to be changed manually. But when I need to change it manually, it causes a StackOverflow exception, because when final.Value is set, it causes interval's ValueChanged event to trigger, which changes final.Value, and so on.

This the ValueChanged handler for startdate and enddate:

    private void dates_ValueChanged(object sender, EventArgs e)
    {
        if (startdate.Value < enddate.Value)
        {
            TimeSpan diff = enddate.Value - startdate.Value;
            DateTime newInterval = new DateTime(startdate.Value.Year, startdate.Value.Month, startdate.Value.Day, diff.Hours, diff.Minutes, diff.Seconds);
            if (interval.Value != newInterval)
                interval.Value = newInterval;
        }
    }

And this is the ValueChanged handler for interval, which causes the StackOverflow exception:

    private void interval_ValueChanged(object sender, EventArgs e)
    {
        int seconds = intervaloDP.Value.Hour * 3600 + intervaloDP.Value.Minute * 60 + intervaloDP.Value.Second;
        finalDP.Value = finalDP.Value.AddSeconds(seconds);
    }

Is there a way to change this code and make it work the way I need it to work?


Solution

  • Make sure that there is always an exit condition:

    var dtm = startDP.Value.AddSeconds(seconds);
    if (dtm != finalDP.Value)
        finalDP.Value = dtm;
    

    This way, the event won't fire if there is no change to make.

    UPDATE: Changed code so that seconds are added to startDP, not finalDP.