How to create a Calendar Control in ASP.NET


Sometimes we need to create a calendar control for displaying date into a textbox or any other control. Here is a simple demo of about creating a calendar control in asp.net.

For doing this activity we need to create a web page with the name Calendar.aspx

Following is the source code for the same.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Calendar.aspx.cs" Inherits="Calendar" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Eco Friend & Co. - Time Tracker - Select Date</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <meta name="generator" content="Microsoft Visual Studio, see http://msdn.microsoft.com/vstudio/" />
    <meta name="Description" content="Select a date" />
    <meta name="copyright" content="Copyright (c) 2011 Eco Friend & Company. All rights reserved."
/>
</head>
<
body>
    <form id="form1" runat="server">
        <div id="calbg">
            <div id="calcontent">
                <fieldset>
                    <legend>SeleSelect a date: </legend>
                    <asp:DropDownList ID="MonthSelect" runat="server" AutoPostBack="True" OnSelectedIndexChanged="MonthSelect_SelectedIndexChanged"></asp:DropDownList>
                    &nbsp;
                    <asp:DropDownList ID="YearSelect" runat="server" AutoPostBack="True" OnSelectedIndexChanged="YearSelect_SelectedIndexChanged">
                    </asp:DropDownList>
                    <asp:Calendar ID="Cal" runat="server" ShowTitle="False" ShowNextPrevMonth="False"
                         DayNameFormat="FirstTwoLetters" FirstDayOfWeek="Sunday"
OnSelectionChanged="Cal_SelectionChanged">
                        <TodayDayStyle Font-Bold="True" ForeColor="White"
BackColor="#990000"></TodayDayStyle>
                        <DayStyle BorderWidth="2px" ForeColor="#666666" BorderStyle="Solid"
BorderColor="White"
                            BackColor="#EAEAEA"></DayStyle>
                        <DayHeaderStyle ForeColor="#649CBA"></DayHeaderStyle>
                        <SelectedDayStyle Font-Bold="True" ForeColor="#333333"
BackColor="#FAAD50"></SelectedDayStyle>
                        <WeekendDayStyle ForeColor="White"
BackColor="#BBBBBB"></WeekendDayStyle>
                        <OtherMonthDayStyle ForeColor="#666666"
BackColor="White"></OtherMonthDayStyle>
                    </asp:Calendar>
                    <br />
                    <table>
                        <tr>
                            <td valign="middle" colspan="2">
                                Date Selected:
                                <asp:Label ID="lblDate" runat="server">
                                </asp:Label>
                                <input id="datechosen" type="hidden" name="datechosen" runat="server">
                            </td>
                        </tr>
                        <tr>
                            <td valign="middle">
                                <asp:Button ID="OKButton" runat="server" Text="OK" />
                             </td>
                            <td valign="middle">
                                <asp:Button ID="CancelButton" runat="server" Text="Cancel" OnClientClick="javascript:self.close()"/>
                            </td>
                        </tr>
                    </table>
                </fieldset>
            </div>
        </div>
    </form
>
</body>
</
html>

Following is the source code of the Calendar.aspx.cs file

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Calendar : System.Web.UI.Page
{
    public string controlToEdit;
    public string isPostBack;

    public Calendar()
    {
        LoadComplete += new EventHandler(Page_LoadComplete);
    }
    void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            controlToEdit = Request.QueryString["controlID"];
            Session.Add("controlToEdit", controlToEdit);
            isPostBack = Request.QueryString["isPostBack"];
            Session.Add("isPostBack", isPostBack);

            // Cast first day of the week from web.config file.  Set it to the calendar
           
//Cal.FirstDayOfWeek = (System.Web.UI.WebControls.FirstDayOfWeek)Convert.ToInt32(ConfigurationManager.AppSettings["FirstDayOfWeek"]);

            // Select the Correct date for Calendar from query string
            // If fails, pick the current date on Calendar
            try
            {
                Cal.SelectedDate = Cal.VisibleDate = Convert.ToDateTime(lblDate.Text);
            }
            catch
            {
                Cal.SelectedDate = Cal.VisibleDate = DateTime.Today;
            }
            // Fills in correct values for the dropdown menus
            FillCalendarChoices();
            SelectCorrectValues();
        }
        else
        {
            if (Session["controlToEdit"] != null)
                controlToEdit = (string)Session["controlToEdit"];
            if (Session["isPostBack"] != null)
                isPostBack = (string)Session["isPostBack"];
        }
    }
    void Page_LoadComplete(object sender, System.EventArgs e)
    {
        OKButton.OnClientClick = "javascript:window.opener.SetControlValue('" + this.controlToEdit + "','" + lblDate.Text + "','" + this.isPostBack + "');";
    }

    protected void FillCalendarChoices()
    {
        DateTime thisdate = (DateTime.Now).AddYears(5);

        // Fills in month values
        for (int x = 0; x < 12; x++)
        {
            // Loops through 12 months of the year and fills in each month value
            ListItem li = new ListItem(thisdate.ToString("MMMM"), thisdate.Month.ToString());
            MonthSelect.Items.Add(li);
            //to add next next month name to the monthselect drop downlist control like aug then sept and so on....
            thisdate = thisdate.AddMonths(1);
        }
 
        // Fills in year values and change y value to other years if necessary
        for (int y = 2000; y <= thisdate.Year; y++)
        {
            YearSelect.Items.Add(y.ToString());
        }
    }
 
    protected void SelectCorrectValues()
    {
        lblDate.Text = Cal.SelectedDate.ToShortDateString();

        datechosen.Value = lblDate.Text;

        MonthSelect.SelectedIndex = MonthSelect.Items.IndexOf(MonthSelect.Items.FindByValue(Cal.SelectedDate.Month.ToString()));

        YearSelect.SelectedIndex = YearSelect.Items.IndexOf(YearSelect.Items.FindByValue(Cal.SelectedDate.Year.ToString()));

    }

    protected void Cal_SelectionChanged(object sender, System.EventArgs e)
    {
        Cal.VisibleDate = Cal.SelectedDate;
        SelectCorrectValues();
    }

    protected void MonthSelect_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        Cal.SelectedDate = Cal.VisibleDate
            = new DateTime(Convert.ToInt32(YearSelect.SelectedItem.Value),
                           Convert.ToInt32(MonthSelect.SelectedItem.Value), 1); ;
        SelectCorrectValues();
    }

    protected void YearSelect_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        Cal.SelectedDate = Cal.VisibleDate
            = new DateTime(Convert.ToInt32(YearSelect.SelectedItem.Value),
                           Convert.ToInt32(MonthSelect.SelectedItem.Value), 1); ;
        SelectCorrectValues();
    }
}

Till now we have created an aspx page and it depends how to open this webpage.  I prefer to open this web page as a popup therefore we will be creating a javascript file with some methods in it.

Following is the source code for the same, save this file with script.js extension

var popUp;

function SetControlValue(controlID, newDate, isPostBack)

{

    popUp.close();

  //document.forms[0]["textBox"].value=0;

  //document.getElementById('<%= textBox.ClientID%>').value=0;

    document.forms[0][controlID].value=newDate;

  // __doPostBack(controlID,'');

}

function OpenPopupPage (pageUrl, controlID, isPostBack)

{

    popUp=window.open(pageUrl+'?controlID='+controlID+'&isPostBack='+ isPostBack,'popupcal', 'width=250,height=330,left=200,top=250');

 }

Now in order to test the functionality we'll be creating a default.aspx page with one textbox control in it. Following is the source code for the same.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript" src="javascript/script.js">
    </script
>
</head>
<
body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
         <a href="javascript:OpenPopupPage('Calendar.aspx','<%= txtDate.ClientID %>','<%= Page.IsPostBack %>');">
                    <img src="images/icon-calendar.gif" /></a>
    </div>
    </form
>
</body>
</
html>

Now just run the web application and click on the calendar icon you will see the following output.

How to create a Calendar Control in ASP.NET

Calendar Control in ASP.NET

Calendar Control in ASP.NET

Now press the ok button. you'll see that the date is displayed in the textbox.

Hope you liked the example.
 

Up Next
    Ebook Download
    View all
    Learn
    View all