May 2, 2011

ASP.Net - Using Calendar Control and Importance of DayRender Event

1. Introduction

The Calendar Control in allows you to pick a date. Why we need a control like this for picking a date that involves navigation when I easily type the date in a specific format in a textbox? Well, so the Calendar control has usually used a calendar and the control is useful when the user wants to do some kind of date scheduling by knowing the Day of the date, weekdays and holidays etc., Now if I ask that a text box control provides all these information, you will answer No.

So, the control is useful on the above-said situation and it is not much useful when you placed it to specify the date of birth for a person. It is upon the developer to decide when to use the control.

When you place a Calendar control on the page, the Initial appearance does not look great. But it still does the basic job selecting a date. We will explore some properties which will make the control look pleasing and then we will move to the coding part of it.

Below is the Initial appearance of the control when you placed it in the page without setting any properties:

2. Setting up the control

Below are the important properties that will be useful to customize the control the way we want.

The ShowHeader Property allows hide/show of the heading of the control. In the above control, the heading is the weekdays displayed below the control Title.

The ShowTitle Property is useful to control showing or hiding the Title of the calendar. The title of the Control shows the Year and present month. And each numbered tile in the control represents the Day. If you need you can display grid lines separating each tile from others using the ShowGridLines property.

The properties NextMonthText, PreviousMonthText is used to set the text or image for the next or previous month navigations. In the above control, the navigation text is set to <= and >=. These texts are actually a link that moves the month in the calendar control backwards or forward. You can also specify an image using the Img Src HTML tag. In the sample, I used the images, have a look at these property values in the downloaded sample.

The SelectionMode property allows how many days can be picked one at a time. The values and the selection behaviour is given below:
Day: You can pick only one date.
Dayweek: You can pick a single day or an entire week. An arrow will be displayed for each week for making the selection. The Selection Link text can be changed to image using the property SelectWeekText

DayWeekMonth: You can pick a single day or Entire week or entire month. In addition to Arrows for Weeks, you will get one more arrow in the top corner to select the entire month. The selection link text can be changed or set to an image using the property SelectMonthText

In the Sample,
I set the SelectionMode property to DayWeekMonth.
The properties NextMonthText, PreviousMonthText, SelectWeekText, SelectMonthText are used to change the arrow keys into images. Have a look at these property values in the sample. Below is the example for NextMonthText from the sample:
<img src='images/NMonth.ico' border=0>

You can set different Background color, foreground color, fonts etc to each part of the control by accessing the following properties:
1) DayHeaderStyle : Day header is the one that displays weekdays name
2) DayStyle: Set style for each normal days in the calendar
3) NextPrevStyle: Set style for the Next and previous month
4) OtherMonthStyle: When a month is displayed in the calendar, there are days that comes from the previous and/or next months. This property sets style for those
5) SelectedDayStyle: Sets the style for the currently selected Day
6) SelectorStyle: Sets the style for the Month and week selectors
7) TitleStyle: Sets the style for the title.
8) TodayDayStyle: Style for the Today’s day
9) WeekDayStyle: Sets style for the Week Days Style.

By setting the above properties, you can make a big difference to the Calendar control, Have a look at these property values in the attached sample application. You no need to look property values for all the 9 properties, just have a look at the one to get an idea.

Below is the customized Calendar control from the Sample:

3. About the Sample

The calendar control displayed above is formatted to have a better look. The arrows in the title allow you to navigate between the months. The diagonal arrow is to select all the dates in the present month. Horizontal arrow will select the entire week. You can also select a single day by clicking on it. Today’s day is highlighted in light green color. The special days (Can be anything, in this sample it is a holiday) are shown in dark green. Days that is not part of the present month is shown in green color. Weekdays are shown in different color.

Below the calendar control is a Panel and Label to display the selected dates. The check boxes allow to show or hide the visual appearance of the calendar control say, Grid Lines, Calendar header and Calendar title.

Look at the screen shot of the sample page shown below:

4. Controlling the Header, title & Grid Lines

At runtime, the property already discussed in section two is set to control the visibility of the Calendar header, Calendar visibility and grid lines separator for the days. Note that once you turn off the grid lines, the BroderStyle property of the nine calendar style (specified in section two) becomes effective. Below is the code for setting the Boolean properties at runtime:

//Calendar 01: Show/Hide Header
protected void chkHeader_CheckedChanged(object sender, EventArgs e)
    Calendar.ShowDayHeader = chkHeader.Checked;

//Calendar 02: Show/Hide GridLine in the Calendar Control
protected void chkGridLines_CheckedChanged(object sender, EventArgs e)
    Calendar.ShowGridLines = chkGridLines.Checked;

//Calendar 03: Show/Hide Calendar Title
protected void chkTitle_CheckedChanged(object sender, EventArgs e)
    Calendar.ShowTitle = chkTitle.Checked;

During the page load event, all the check boxes are set in the checked state. Also, the calendar’s header, title, gridlines are turned on. Below is the code for it:

//Calendar 04: Set the Default Properties
protected void Page_Load(object sender, EventArgs e)
    if (Page.IsPostBack == false)
        Calendar.ShowDayHeader = true;
        Calendar.ShowGridLines = true;
        Calendar.ShowTitle = true;
        chkGridLines.Checked = true;
        chkHeader.Checked = true;
        chkTitle.Checked = true;

5 Selection Changed Event

Remember that the Selection Mode property of the calendar control was set to DayWeekMonth. So the control allows you select multiple dates by Week selector (Horizontal Arrows) and the Month Selector (Diagonal Arrow). You can also select a single day. In all these cases selection changed event is fired. The handler for that event is the perfect place for listing the selected date. Below is the code for it:

//Calendar 05: Get the Selected Date(s) and display it in the Label
protected void Calendar_SelectionChanged(object sender, EventArgs e)
    string date_str = "";
    int count = 0;

    foreach (DateTime dt in Calendar.SelectedDates)
        date_str = date_str + "Selected Date #" + count.ToString() + ": " +
            dt.ToShortDateString() + "<br/>";

    lblDisplay.Text = date_str;

Note the usage of the <br/> as the ASP.Net label control does not interpret the Newline character properly.

6. Marking the Special Days and DayRender Event

Marking the special days is a kind of action that should be tied with the month navigation. That’s how we will see it initially. But there is an event for this task. The event is DayRender. The event is fired when each Day in the calendar control is drawn. So the handler can make use of the passed-in event argument to control the display of the Day part of the calendar control.

From the passed-in event argument, you can get the CalendarDay and TableCell objects. CalendarDay can be accessed by Day property and TableCell can be accessed by the Cell property of the event argument. From the CalendarDay object, you can know the date it belongs and all parts of the date. With TableCell object you can control the visual attributes of the single day. Here we are setting the special day using the TableCell property, and to know whether the cell belongs to the special day we need the CalendarDay.

Below is the code for the DayRender and I set a special day for the month of April only. Change the logic to set it for the entire year and I just want to show an example only here.

//Calender 06: When displaying the Day part of the control, make sure to adjust
//              the Day portion of the calendar control to dsplay special date.
//              Let me do it for April 5,14,18 as holiday. For full year you should
//              apply you own logic. Use a string manipulation or 2D array to do it
//              efficiently.
protected void Calendar_DayRender(object sender, DayRenderEventArgs e)
    //Display the date differently when it is a holiday
    if (e.Day.Date.Month == 4)
        if (e.Day.Date.Day == 5 || e.Day.Date.Day == 14 || e.Day.Date.Day == 18)
            e.Cell.ForeColor = Color.Azure;
            e.Cell.BackColor = Color.Green;
            e.Cell.Font.Bold = true;

7. Closure calendar control does not support year wise navigation. To do so, you should derive your own class. So make sure before using it. If you provide the same above control to your user for selecting their date of birth, they will beat your manager.

8. How Do I open the Attached Project?

1) Download the attached zip file
2) Extract it to a folder
3) Open visual studio 2005
4) Click the menu item File|Open|Web site
5) Select the Extracted Folder

Note: The Attached solution is created in visual studio 2005. If you have the latest version say yes to the conversion wizard

Source Code : Download


  1. How would u do it if u want to add event details in the table cell?
    For example, u actually want the special day cell to depict the name of the event, like "independence day", "thanks giving" etc.

  2. It will be not good when you display Holiday details in the cell itself. Below is the detail however:
    Code Snippet to Look for,
    //Calender 06:

    e.Cell.text = Some2dStringArray[Month][Day]; //The 2d array may already be populated by you with description. And the special day entry in the array has valid string. Others will have empty.

    The Nice way is Handling the Selection changed to Display the special day. If you look for mouse move over the special cell should display the Holiday details.. Well, it needs the control should be extended by yourself


Leave your comment(s) here.

Like this site? Tell it to your Friend :)