Unleashing ASP.net Calendar Control

Download Sample CalendarDemo.zip (171.18 kb)

Introduction

Calendar control is as important as a normal text box control in any application. Most of any application which needs data entry will definitely need a calendar control at some part. ASP.net has a very good calendar control which we often ignore without exploring how far it can be programmed / customized.

Calendar control in ASP.net definitely have few shortcoming on few unusual and complex scenario but over this article, I will try to address and achieve few functionalities / UI which we would normally need in our day to day programming.

There are two important properties “SelectedDate” and “SelectedDates” which will get or set the currently selected date and set of selected dates (if multiple select is made) respectively. We will use these properties through out our sample to get our necessities achieved.

 

Different Selection Types of ASP.net Calendar

A calendar control can be roughly made to select by day / week /month by setting the “Selection Mode” property of the control.

Day Selection Mode

By default a calendar is set to make a day selection. i.e., you can select a single day on the calendar. When you try to select other date, the previous date will get deselected. The default value with no selection will be the minimum value of the “DateTime” type.Day Selection Calendar

 

Day / Week Selection Mode

In this mode you are allowed to select a single date or an entire week. By default the property “SelectWeekText” shows “>” which can be changed to whatever you want to. The “SelectedDates” property will have the entire week dates when a week is selected.Week Selection Calendar

 

Day / Week / Month Selection Mode

In addition with the previous mode, the selection allows you to select an entire month. By default the property “SelectWeekText” shows “>>” .Month Selection Calendar

 

None

As the name indicates, this is nothing but a read-only mode calendar.

 

Multi Date Select ASP.net Calendar

For any multi select calendar, you will need to set the dates that you have to select in the “SelectedDates” property. This property accepts any valid date and adds it to it’s own collection and select the same on the control. When you set the dates using the code, please understand that ASP.net calendar doesn’t validate if the same date is specified multiple times and therefore if you are dealing with a bigger list of dates, then it is advised that you implement the same logic in your code as in our sample. The date will be selected, no matter you specify any number of times more than once.

Multi Date Selection Calendar

 In our sample, the logic is drafted in the method “SetMultiDateCalendar” explains the logic behind doing this. Our sample converts a day to a toggle select / deselect date.

 

From To Date ASP.net Calendar

This is pretty much the need in most of our scenarios where we want to enter a “from” and “to” date using calendar. In the sample I have demonstrated how this can be done using a single calendar. Once again we will take the support of the “SelectedDates” property to get this achieved.

Below are the simple rules followed in the algorithm I have written for getting this functionality.

  • When a single date is selected, it will be considered as both “from” and “to date”.
  • If you go ahead and select a greater date, then it will be considered as the “to date”.
  • After selecting both “from” and “to date”, a new selection is made then it will be considered as new selection and older selection will be removed.
  • The dates from the “from” till “to” date will show as selected.

From To Date Selection Calendar

 If you are planning to use the same in your application, then I would seriously advice you to use it as a user control instead of writing the same code again and again everywhere.

You will also need to use two properties “From Date” and “To Date” which will ease the implementation of the controls. The same can be written as below.

 

        /// <summary>
        /// Gets or sets from date.
        /// </summary>
        /// <value>From date.</value>
        public DateTime FromDate
        {
            get
            {
                if (this.FromToDateCalendar.SelectedDates.Count != 0)
                {
                    return this.FromToDateCalendar.SelectedDates[0];
                }

                return DateTime.MinValue;
            }
            set
            {
                this.FromToDateCalendar.SelectedDate = value;
                this.SetFromToDateCalendar();
            }
        }

        /// <summary>
        /// Gets or sets to date.
        /// </summary>
        /// <value>To date.</value>
        public DateTime ToDate
        {
            get
            {
                if (this.FromToDateCalendar.SelectedDates.Count != 0)
                {
                    return this.FromToDateCalendar.SelectedDates[this.FromToDateCalendar.SelectedDates.Count - 1];
                }

                return DateTime.MinValue;
            }
            set
            {
                this.FromToDateCalendar.SelectedDate = value;
                this.SetFromToDateCalendar();
            }
        }

ASP.net Calendar as Outlook Calendar

This is a serious necessity in few applications where you want to show the appointments over a calendar. Though most of us are not aware, ASP.net calendar provides an easier way to deal with this.

In our sample I have created a class “Schedule” with a “EngagementTime” and “Description” as property and the collection will depict appointments I have over the calendar. I have written a method which will create few mock data which I will use for binding.

To understand how to customize the calendar control similar to look like an appointments calendar in Outlook, we will need to understand how the control is rendered. An ASP.net calendar is nothing but a table with cells which are days. The Calendar control has an event called “DayRender” which is raised whenever a day is rendered or to put it simple, it is raised whenever a cell for the calendar control is rendered.

A “DayRenderEventArgs” has useful properties like “Cell” which is of Type “TableCell”, “Day” which is of type “CalendarDay” (which will help you determining the date it is binding and many other trivial details about what is it inside the calendar” and “SelectUrl” which can be set if you need a different url to which the post back has to be set for that particular cell.

In our example, we have taken the advantage of both “Day” and “Cell” property to find the appointments for that particular day and then use “Cell” to add dynamically created labels which is displays the appointments.

Below is how our render event look like.

 

/// <summary>
        /// Handles the DayRender event of the OutlookCalendar control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.DayRenderEventArgs"/> instance containing the event data.</param>
        protected void OutlookCalendar_DayRender(object sender, DayRenderEventArgs e)
        {
            try
            {
                if (schedules.Where(item => item.EngagementTime.ToString("d") == e.Day.Date.ToString("d")).Count() > 0)
                {
                    // Get the schedules for the current day
                    List daySchedules = schedules.Where(item => item.EngagementTime.ToString("d") == e.Day.Date.ToString("d")).ToList();

                    foreach (Schedule schedule in daySchedules)
                    {
                        Label engagement = new Label();
                        engagement.Text = string.Format("{0:t} - {1}", schedule.EngagementTime, schedule.Description);

                        Literal lineBreak = new Literal();
                        lineBreak.Text = "<br />";

                        e.Cell.Controls.Add(lineBreak);
                        e.Cell.Controls.Add(engagement);
                        e.Cell.HorizontalAlign = HorizontalAlign.Left;
                    }

                    // check if the day has more than 1 appointment and mark as busy if it is.
                    if (daySchedules.Count() > 1)
                    {
                        e.Cell.BackColor = Color.Red;
                        e.Cell.ToolTip = "Busy day.";
                    }
                }
            }
            catch (Exception ex)
            {
                this.HandleException(ex);
            }
        }

Outlook Calendar

If you can look at the code, the “Outlook Calendar” which we have achieved here is one simple application of ASP.net calendar and the functionalities you can achieve using the ASP.net calendar is as much as your imagination.

I hope that this post gave you some insight over the ASP.net calendar is capable of doing and how easily you can customize it achieve greater functionalities.

Download Sample CalendarDemo.zip (171.18 kb)

Unleashing ASP.net Calendar Control

9 thoughts on “Unleashing ASP.net Calendar Control

  1. That's the way it goes, spend 3 hours looking for the answer to a problem, go home for the weekend with the problem unresolved, come in on Tuesday(3 day weekend), and find the answer in the first search. Adding the literal control to the calendar solved the problem I was having with the date not acting as a link.

    Thanks for the answer.

    chuck

  2. I had a similar linking problem with my calendar. Thanks for the post. Gave some keen insight on how to control the calendar. Great post!!

  3. This is an amazing one, I would say!
    I specially liked the outlook thingy with Asp.net calendar control. I've worked with this control very much, but as you said, not many are familiar with this outlook like functionality, including me. 🙂

  4. Excellent post. Very straight forward and an excellent use of lists to boot!!

    Thanks a bunch.
    -Michael

  5. Error 1 Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive. C:RajacalenCalendarDemoCalendarDemoWeb.config 19
    Hi,
    targetFramework="4.0"

    I am using old version and i am getting error as shown above. I need to know wether i cant use this code in my studio.
    PLease help asap.

    Regards

    Chella

  6. Please download and install .net framework 4.0 If you dont have VS2010, then you can safely remove targetFramework="4.0"
    from the web.config

    Remember the VS2010 Express is free for non-commercial development.

Leave a Reply to Michael Cancel reply

Scroll to top
%d bloggers like this: