Search code examples
c#winformsmonthcalendar

Problem with DateChanged event on MonthCalendar


Tried googling, but cannot really find an answer.

Having a Windows Form with a MonthCalendar control and handling of the DateChanged event. the problem is related to change of month by mouse click.

I tried having a counter value shown in a label, which is counted up every time the event handler is called. When month is changed the event handler is called 2 times.

When MessageBox.Show("anything") is called at event handling, the event handler seems to get recalled several times and the calendar starts changing one month backward forever.

Do anybody know why?

Following code in the windows form class results in the described behaviour:

private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
    int i = int.Parse(labelDateChanged.Text);
    labelDateChanged.Text = (i + 1).ToString();
    MessageBox.Show(i.ToString());
}

private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
    int i = int.Parse(labelDateSelected.Text);
    labelDateSelected.Text = (i + 1).ToString();
}

Solution

  • Not catching ALL DateChanged events, but a solution is to handle DateChanged, KeyUp, and MouseUp events.

    The DateChanged event sets a bool IsDateChanged to true. KeyUp and MouseUp event handling checks if IsDateChanged and executes the code necessary + sets IsDateChanged to false.