It is holiday in cold Canada so today’s tip is a 5 minutes “how to”. Let’s check how to populate a windows month calendar control with holidays.
The month calendar control exposes three properties to set special dates. All of them are collection of dates and have different behaviors:
- AnnuallyBoldedDates: Defines dates that appears once a year and has a yearly recurrence. i.E. If you add the date 12/25/2008, the system ignores the year and every December 25th the date will be bold;
- BoldedDates: Defines dates that appears bolded just once. i.E. 09/28/2008 displays the date as bold but 09/28/2009 is not affected;
- MonthlyBoldedDates: Defines monthly dates that appears bolded. i.E. 08/16/2008 makes every 16th to be bolded.
How to set in design-time
For those that have developed at least one application with Visual Studio the properties window is a well-known window.
After you have added the calendar to your application’s form, select the calendar control and click on the button with the three dots close on the right side of the property value as demonstrated on the picture 1:
The DateTime Collection Editor window will be displayed. Using the button Add set the date you need on the right side. Once this process is done, click the OK button. To remove an item from the collection, click Remove. The picture 2 shows de DateTime Collection Editor:
How to set programmatically
You may have a lot of ways to storage and retrieve the holiday’s dates. Database, XML files are just two examples of sources that you can read from. Once you read this information, you need:
- Create an array of dates;
- Assign the array of dates to the desired property as described previously.
Example 1 – Array of dates
DateTime holidays = new DateTime;
holidays = new DateTime(2008, 12, 25);
holidays = new DateTime(2008, 1, 1);
holidays = new DateTime(2008, 7, 4);
holidayCalendar.AnnuallyBoldedDates = holidays;
Example 2 – Generic list of DateTime objects
List<DateTime> holidays = new List<DateTime>()
new DateTime(2008, 12, 25),
new DateTime(2008, 1, 1),
new DateTime(2008, 7, 4)
holidayCalendar.AnnuallyBoldedDates = holidays.ToArray();
Remove bolded dates in runtime
The month calendar control provides some methods to remove bolded dates as described below:
- RemoveAllAnnuallyBoldedDates(): Removes all items from the annually bolded dates collection;
- RemoveAnnuallyBoldedDate(DateTime date): Removes a specific date from the annually bolded date collection;
- RemoveAllBoldedDates(): Removes all items from bolded dates collection;
- RemoveBoldedDate(DateTime date): Removes a specific date from the bolded date collection;
- RemoveAllMonthlyBoldedDates(): Removes all items from the monthly bolded dates collection;
- RemoveMonthlyBoldedDate(DateTime date): Removes a specific date from the monthly bolded date collection.