Click here to Skip to main content
Click here to Skip to main content

Customizing the ASP.NET Calendar Control

By , 21 Jul 2011
 

Introduction

Recently for a project, I had to use the ASP.NET Calendar control to allow the user to enter their date of birth. I found that the calendar control is good for selecting a date from current, next, or previous month, and when entering a date of birth, it would need so many navigations to get to the right date. This was not feasible.

Below we will see how to make the Calendar control more flexible in terms of its navigation through the addition of two drop-down lists. First, create a User Control so that the customized Calendar control can be used on an .aspx page.

I have attached a simple project which guides you on how to use the customized Calendar control to enter a date of birth.

Customizing the Calendar Control

  1. First the add an ASP.NET Calendar control with some styles applied.
  2. <asp:Calendar ID="calDate" runat="server"
        BackColor="White" BorderColor="#3366CC"  CellPadding="1" DayNameFormat="Shortest"
        Font-Names="Verdana" Font-Size="8pt" ForeColor="#003399" Height="200px" 
        Width="250px" ondayrender="calDate_DayRender">
        <SelectedDayStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
        <TodayDayStyle BackColor="#99CCCC" ForeColor="White" />
        <SelectorStyle BackColor="#99CCCC" ForeColor="#336666" />
        <WeekendDayStyle BackColor="#CCCCFF" />
        <OtherMonthDayStyle ForeColor="#999999" />
        <NextPrevStyle Font-Size="8pt" ForeColor="#CCCCFF" />
        <DayHeaderStyle BackColor="#99CCCC" ForeColor="#336666" Height="1px" />
        <TitleStyle BackColor="#003399" BorderColor="#3366CC" 
            BorderWidth="1px" Font-Bold="True"
            Font-Size="10pt" ForeColor="#CCCCFF" Height="25px" />
    </asp:Calendar>
  3. Add dropdown lists for month and year lists.
  4. For month dropdown, hardcode the data in the Design page only; for year dropdown, bind the data in the code-behind.

    <asp:DropDownList ID="Ddyear" runat="server" AutoPostBack="True" 
        onselectedindexchanged="DdyearSelectedIndexChanged">
    </asp:DropDownList>
    <asp:DropDownList ID="Ddmonth" runat="server" AutoPostBack="True" 
        onselectedindexchanged="DdmonthSelectedIndexChanged">
         <asp:ListItem Value="00">*Month*</asp:ListItem>
        <asp:ListItem Value="01">Jan</asp:ListItem>
        <asp:ListItem Value="02">Feb</asp:ListItem>
        <asp:ListItem Value="03">March</asp:ListItem>
        <asp:ListItem Value="04">april</asp:ListItem>
        <asp:ListItem Value="05">May</asp:ListItem>
        <asp:ListItem Value="06">June</asp:ListItem>
        <asp:ListItem Value="07">July</asp:ListItem>
        <asp:ListItem Value="08">August</asp:ListItem>
        <asp:ListItem Value="09">Sept</asp:ListItem>
        <asp:ListItem Value="10">Oct</asp:ListItem>
        <asp:ListItem Value="11">Nov</asp:ListItem>
        <asp:ListItem Value="12">Dec</asp:ListItem>
    </asp:DropDownList>
  5. For year dropdown, data bind on the page load event:
  6. protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack) return;
        else
        {
            var al = new ArrayList();
            al.Add("*Year*");
            for (var i = 1900; i <=2011; i++)
            {
                al.Add(i);
            }
            Ddyear.DataSource = al;
            Ddyear.DataBind();
        }
    }
  7. These dropdown lists will be added to the calendar header by overriding the Render method. Previous month navigation icon (i.e., ‘<’ on the left side of the calendar header) is replaced by the month dropdownlist. Next, the month navigation icon (i.e., ‘>’ on the right side of the calendar header) is replaced by the year dropdownlist. In the middle of the calendar header, the selected month name and year will be displayed (e.g.: March 1989).
  8. #region Regular expressions
    private static Regex regPrevMonth = new Regex(
            @"(?<PrevMonth><a.*?><</a>)",
            RegexOptions.IgnoreCase
            | RegexOptions.Singleline
            | RegexOptions.CultureInvariant
            | RegexOptions.IgnorePatternWhitespace
            | RegexOptions.Compiled
            );
     
    private static Regex regNextMonth = new Regex(
            @"(?<NextMonth><a.*?>></a>)",
            RegexOptions.IgnoreCase
            | RegexOptions.Singleline
            | RegexOptions.CultureInvariant
            | RegexOptions.IgnorePatternWhitespace
            | RegexOptions.Compiled
            );
    #endregion
     
    protected override void Render(HtmlTextWriter writer)
    {
        // turn user control to html code
        string output = CalControl1.RenderToString(calDate);
                
        MatchEvaluator mevm = new MatchEvaluator(AppendMonth);
        output = regPrevMonth.Replace(output, mevm);
               
        MatchEvaluator mevb = new MatchEvaluator(AppendYear);
        output = regNextMonth.Replace(output, mevb);
        // output the modified code
        writer.Write(output);
    }
    
    public static string RenderToString(Control c)
    {
        bool previousVisibility = c.Visible;
        c.Visible = true; // make visible if not
     
        // get html code for control
        System.IO.StringWriter sw = new System.IO.StringWriter();
        HtmlTextWriter localWriter = new HtmlTextWriter(sw);
        c.RenderControl(localWriter);
        string output = sw.ToString();
     
        // restore visibility
        c.Visible = previousVisibility;
     
        return output;
    }
    
    private string AppendMonth(Match m)
    {
        return CalControl1.RenderToString(Ddmonth) + " " ;
    }
          
    private string AppendYear(Match m)
    {
        return  " " + CalControl1.RenderToString(Ddyear);
    }
  9. Initially, the calendar shows the current date, and then it displays whichever date you select.
  10. The code to set the current date to show initially is as below:

    public DateTime? SelectedDate
    {
        get
        {
            // null date stored or not set
            if (ViewState["SelectedDate"] == null)
            {
                return null;
            }
            return (DateTime)ViewState["SelectedDate"];
        }
        set
        {
            ViewState["SelectedDate"] = value;
            if (value != null)
            {
                calDate.SelectedDate = (DateTime)value;
                calDate.VisibleDate = (DateTime)value;
            }
            else
            {
                calDate.SelectedDate = new DateTime(0);
                calDate.VisibleDate = DateTime.Now.Date;
            }
        }
    }
  11. Finally, the event handler code for DayRender, DdmonthSelectedIndexChanged, and DdyearSelectedIndexChanged are as follows:
  12. protected void calDate_DayRender(object sender, DayRenderEventArgs e)
    {
        HyperLink hlnk = new HyperLink();
        hlnk.Text = ((LiteralControl)e.Cell.Controls[0]).Text;
        hlnk.Attributes.Add("href", "javascript:SetDate('" +
        e.Day.Date.ToString("dd/MM/yyyy") + "')");
        e.Cell.Controls.Clear();
        e.Cell.Controls.Add(hlnk);
    }
    
    protected void DdyearSelectedIndexChanged(object sender, EventArgs e)
    {
       var syear = DateTime.Now.Year;
       var smonth = DateTime.Now.Month;
       if (Ddmonth.SelectedValue != "00")
       {
           smonth = Convert.ToInt32(Ddmonth.SelectedValue);
       }
       if (Ddyear.SelectedValue!="*Year*")
       {
           syear = Convert.ToInt32(Ddyear.SelectedValue);
       }
       var date = smonth + "/" + DateTime.Now.Day + "/" +syear;
       var dateTime = Convert.ToDateTime(date);
       calDate.VisibleDate = dateTime;
    }
    
    protected void DdmonthSelectedIndexChanged(object sender, EventArgs e)
    {
        var smonth = DateTime.Now.Month;
        var year = DateTime.Now.Year;
        if (Ddyear.SelectedValue != "*Year*")
        {
            year = Convert.ToInt32(Ddyear.SelectedValue);
        }
        if (Ddmonth.SelectedValue != "00")
        {
            smonth = Convert.ToInt32(Ddmonth.SelectedValue);
        }
        var sdate = smonth + "/" + DateTime.Now.Day + "/" + year;
        calDate.VisibleDate = Convert.ToDateTime(sdate);
    }

The above code completes customizing the Calendar control. Now we will look at a simple example to see how to use this control to enter date of birth data. (The complete source code is available for download at the top of this article.)

  1. In the first page (calendar.aspx), create a textbox for date of birth data and an image button or anchor tag to open a calendar on popup onclick. Pass the textbox ID to the popup to assign the selected date to the textbox.
  2. <asp:textbox id="tbMyDate" runat="server" Width="80px"></asp:textbox>
    <a href="" onclick="return PopupPicker('tbMyDate')">
    <img src="Images/Calendar_scheduleHS.png" alt="Picture" border="0"></a>

    Here is the JavaScript to open a popup:

    function PopupPicker(ctl) {
        var PopupWindow = null;
        PopupWindow = window.open('PopupCalendar.aspx?Ctl=' + ctl, 
                                  'PopupWindow', 'width=10,height=250,resizable=yes');
        PopupWindow.focus();
        return false;
    };
  3. In the PopupCalendar.aspx page, we need to register the user control which customized the calendar. And we need to handle the SetDate() JavaScript function  which calls the selecting date function from the calendar. It assigns the selected date to the DOB textbox and closes the popup. See the calDate_DayRender method definition.
  4. <%@ Register src="CalControl1.ascx" tagname="CalControl1" tagprefix="uc2" %>
    <uc2:CalControl1 ID="CalControl11" runat="server" />
     function SetDate(dateValue) {
         ctl = window.location.search.substr(1).substring(4);
         thisForm = window.opener.document.forms[0].elements[ctl].value = dateVae;
         self.close();
     }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rachana BG
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionjavascript not workingmemberVishal Pand3y9 May '13 - 0:04 
i tried to take some help with above article but javascript is not working in code
 function SetDate(dateValue) {
            
            // retrieve from the querystring the value of the Ctl param,
            // that is the name of the input control on the parent form
            // that the user want to set with the clicked date
            ctl = window.location.search.substr(1).substring(4);
            // set the value of that control with the passed date
            thisForm = window.opener.document.forms[0].elements[ctl].value = dateValue;
            // close this popup
            self.close();
            
        }
in javascript console it shows error Uncaught TypeError: Cannot read property 'document' of null PopupCalendar.aspx:10
SetDate PopupCalendar.aspx:10
(anonymous function)
 
any suggestion...
AnswerRe: javascript not workingmemberRachana BG9 May '13 - 4:17 
Hi Try by setting caleder.aspx as start page or executing caleder.aspx page....dont navigate to popupCalandar.aspx.
QuestionIssue in month selectionmemberAnnuKumari7 Mar '13 - 2:19 
when i selecting month from dropdown list it displaying always july month on calender
 
http://s.codeproject.com/script/Forums/Images/smiley_frown.gif
GeneralMy vote of 5memberPrasyee30 Oct '12 - 3:34 
nice
QuestionPostbacksmembersnakewine11 Oct '12 - 5:17 
Seems if the target textbox is READONLY or DISABLED, on the Postback, the server doesn't recognize the change in value.
AnswerRe: Postbacksmembersnakewine11 Oct '12 - 6:34 
the fix... err hack... for me anyway, was to read the "real" value from the form collection on the postback:
 
tbMyDate.Text = Request.Form["tbMyDate"].ToString();
 
Works wonders ! Smile | :)
GeneralMy vote of 5membersnakewine10 Oct '12 - 11:49 
works as promised! Simple to implement - whats not to love??
GeneralLove it man - great job!membersnakewine10 Oct '12 - 11:47 
Subject line says it all Smile | :)
Answercan i get this calendar in multilanguage?? please rply soon...memberRachana BG23 Sep '12 - 21:11 
snehal shejale
Refer This Link
http://stackoverflow.com/questions/1959451/various-calendars-in-the-asp-net-calendar-control
QuestionNot showing date in textbox using masterpage.memberpraveenfds30 Jul '12 - 6:41 
I download this source code, its working fine in normal aspx page. when i tried to use in master.content page, it showing the popupcalender window but date is not displaying in the textbox.
AnswerRe: Not showing date in textbox using masterpage.memberAlRosner9 May '13 - 16:51 
Yes, I noticed the same thing. THe master page mangles the textbox control name so this demo does not work with a master page
GeneralRe: Not showing date in textbox using masterpage.memberRachana BG9 May '13 - 20:53 
Use below code in calender.aspx page.to show selected date in textbox,
 

<script type="text/javascript" language="javascript">
    var ct1 = "<%=tbMyDate.ClientID%>";
    function PopupPicker() {
 
        var PopupWindow = null;
        PopupWindow = window.open('PopupCalendar.aspx?Ctl=' + ct1, 'PopupWindow', 'width=10,height=250,resizable=yes');
        PopupWindow.focus();
       return false;
    };
    </script>
 
     <asp:textbox id="tbMyDate" runat="server" Width="80px"></asp:textbox>
  <a href="" onclick="return PopupPicker()"><img src="Images/Calendar_scheduleHS.png" alt="Picture" border="0"></a>

QuestionError ContontrolsExersise.calendermemberMinhhaipr24 Dec '11 - 21:39 
I downloaded and using test display error could not load type "ContontrolsExersise.calender".
please help me fix this error.
thanks !
minhhai

AnswerRe: Error ContontrolsExersise.calendermemberRachana BG25 Dec '11 - 19:06 
Open in vs2010..It works fine for me I dowloaded same code.
GeneralRe: Error ContontrolsExersise.calendermemberVishal Pand3y8 May '13 - 19:56 
i am also having the same problem this is because mine project is a website not a web application any solution for that ???
QuestionError in popupmemberORolando22 Jul '11 - 0:21 
Hi namerachana,
 
I click calendar icon on calendar.aspx and popup window is opened. it seems ok but it can be shown using javascript in my opinion. When I select month or year from dropdownlist in popup window, an error raised and said "String was not recognized as a valid DateTime". It is a simple error, but I recommend test your code again. If I'm wrong, please inform me.
 
Thanks,
Onur
ORolando..

AnswerRe: Error in popupmembernamerachana22 Jul '11 - 2:27 
Hi
After testing only i attached my project,I downloaded attached project and executed its working fine now also.
AnswerRe: Error in popupmemberbillgatesvijay22 Jul '11 - 2:40 
Onur,
i downloaded same code. it is working fine in my machine.
 
Thanks
Vijayan

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 21 Jul 2011
Article Copyright 2011 by Rachana BG
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid