I need to highlight the dates in a MonthCalendar depending on the data I get from a database, but it keeps throwing me an OutOfMemory exception. I get the days which I have to highlight from database as bool values like this:
command.CommandText = "SELECT Monday FROM Days WHERE Event = "+idEvent+"";
Monday = Convert.ToBoolean(command.ExecuteScalar());
Similar code is used for each day of the week. The range in which I have to highlight the dates is entire year (start and end are the first and the last day of the year, both of DateTime type). I tried to do it with this code:
for (DateTime day = start; day < end; day.AddDays(1))
{
if (Monday && day.DayOfWeek == DayOfWeek.Monday)
{
dates.Add(day);
}
else if (Tuesday && day.DayOfWeek == DayOfWeek.Tuesday)
{
dates.Add(day);
}
else if (Wednesday && day.DayOfWeek == DayOfWeek.Wednesday)
{
dates.Add(day);
}
else if (Thursday && day.DayOfWeek == DayOfWeek.Thursday)
{
dates.Add(day);
}
else if (Friday && day.DayOfWeek == DayOfWeek.Friday)
{
dates.Add(day);
}
else if (Saturday && day.DayOfWeek == DayOfWeek.Saturday)
{
dates.Add(day);
}
else if (Sunday && day.DayOfWeek == DayOfWeek.Sunday)
{
dates.Add(day);
}
}
monthCalendar1.BoldedDates = dates.ToArray();
The point of this algorithm is to bold the dates on which the selected event occurs (every event occurs periodically entire year, with some exceptions like holidays or some specific time interval). So for each event there could be over 200 occurrences a year. How can I solve this problem?
One possible reason is that your iteration code is faulty in that
day.AddDays(1)does not operate in place. it returns a newDateTimeon which the operation has been done.Therefore the value of
daynever changes and your loop is running infinitely.Use a while loop instead: