Click here to Skip to main content
Licence CPOL
First Posted 13 Aug 2007
Views 64,850
Downloads 954
Bookmarked 39 times

DatePicker in ASP.NET 2.0 and AJAX Control Toolkit

By | 13 Aug 2007 | Article
Add a date picker to your ASP.NET 2.0 applications
Screenshot - AJAXCalendar.jpg

Introduction

In this article, we will see how can we add AJAX technology to web user control and get the date from a calendar control. I saw many articles on date-time picker controls, but I did not find one that was useful for picking the month and year through dropdowns. Of the ones that I found, most were paid. My customer needed something like that, but for free. Furthermore, some options do not provide property nullable dates. Here, I introduce "Clear Date" and a property called Nullable.

Create a New AJAX-enabled Web Project

Add new web user control named "DateTimePicker" or whatever else you want. In the HTML of the web control, add the following code so that your control in design mode should look like the image below.

Screenshot - DesignTime.jpg

The HTML

<!-- HTML Code -->

Date:<asp:TextBox ID="DateTextBox" runat="server" 
    Width="150" autocomplete="off" /> 
<br /> 
<asp:Panel ID="Panel1" runat="server" CssClass="popupControl" 
    BorderStyle="solid" BackColor="AliceBlue" BorderColor="darkblue" 
    BorderWidth="1"> 
    <asp:UpdatePanel runat="server" ID="up1"> 
        <ContentTemplate> 
        <center> 
            <asp:DropDownList ID="ddlMonth" runat="server" 
                OnSelectedIndexChanged="ddlMonth_SelectedIndexChanged" 
                AutoPostBack="true" Width="90"> 
                <asp:ListItem Value="1">January</asp:ListItem> 
                <asp:ListItem Value="2">February</asp:ListItem> 
                <asp:ListItem Value="3">March</asp:ListItem> 
                <asp:ListItem Value="4">April</asp:ListItem> 
                <asp:ListItem Value="5">May</asp:ListItem> 
                <asp:ListItem Value="6">June</asp:ListItem> 
                <asp:ListItem Value="7">July</asp:ListItem> 
                <asp:ListItem Value="8">August</asp:ListItem> 
                <asp:ListItem Value="9">September</asp:ListItem> 
                <asp:ListItem Value="10">October</asp:ListItem> 
                <asp:ListItem Value="11">November</asp:ListItem> 
                <asp:ListItem Value="12">December</asp:ListItem> 
            </asp:DropDownList> 
            <asp:DropDownList ID="ddlYear" runat="server" 
                OnSelectedIndexChanged="ddlYear_SelectedIndexChanged" 
                AutoPostBack="True" Width="60"> 
            </asp:DropDownList> 
            
            <asp:Calendar ID="Calendar1" runat="server" Width="150px" 
                DayNameFormat="Shortest" BackColor="White" 
                BorderColor="#3366CC" CellPadding="0" Font-Names="Verdana" 
                Font-Size="8pt" ForeColor="#003399" 
                OnSelectionChanged="Calendar1_SelectionChanged" 
                ShowNextPrevMonth="False" ShowTitle="False" BorderWidth="1px"
                FirstDayOfWeek="Sunday" Height="150px" 
                SelectedDate="2007-08-08"> 
                <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" Font-Size="10pt" 
                    BorderColor="#3366CC" Font-Bold="True" BorderWidth="1px" 
                    ForeColor="#CCCCFF" Height="25px" /> 
            </asp:Calendar> 
            <asp:LinkButton ID="lbtnToday" runat="server" Text=":: Today">
                </asp:LinkButton>    
            <asp:LinkButton ID="lbtnClearDate" runat="server" 
                Text="::Clear Date"></asp:LinkButton> 
        </center> 
        </ContentTemplate> 
    </asp:UpdatePanel> 
</asp:Panel> 
<ajaxToolkit:PopupControlExtender ID="PopupControlExtender1" runat="server" 
    TargetControlID="DateTextBox" PopupControlID="Panel1" Position="Bottom" />

<!-- HTML Code End -->

The Source

'Your Source code in code behind of the web user control look like this

Partial Class DateTimePicker
    Inherits System.Web.UI.UserControl

#Region "Private and Default values"
    Private mCulture As String = "en-GB"
    Private mSelectedDateFormat As String = "dd/MM/yyyy"
    Private mYearMinimum As Integer = 1970
    Private mYearMaximum As Integer = 2029
    Private mNullable As Boolean = True

#End Region

#Region "Public Properties"

    Public Property Nullable() As Boolean
        Get
            Return mNullable
        End Get
        Set(ByVal value As Boolean)
            mNullable = value
        End Set
    End Property

    Public Property Culture() As String
        Get
            Return mCulture
        End Get
        Set(ByVal value As String)
            mCulture = value
        End Set
    End Property

    Public Property SelectedDateFormat() As String
        Get
            Return mSelectedDateFormat
        End Get
        Set(ByVal value As String)
            mSelectedDateFormat = value
        End Set
    End Property

    Public WriteOnly Property YearMinimum() As Integer
        Set(ByVal value As Integer)
            mYearMinimum = value
        End Set
    End Property

    Public WriteOnly Property YearMaximum() As Integer
        Set(ByVal value As Integer)
            mYearMaximum = value
        End Set
    End Property

    Public Property SelectedDate() As DateTime
        Get
            If DateTextBox.Text <> "" Then
                Return DateTime.Parse(DateTextBox.Text, _
                    New System.Globalization.CultureInfo(mCulture))
            Else
                Return Nothing
            End If
        End Get
        Set(ByVal value As DateTime)
            DateTextBox.Text = value.ToString(mSelectedDateFormat, _
                New System.Globalization.CultureInfo(mCulture))
        End Set
    End Property

#End Region

#Region "private and protected methods"

    Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, _
        ByVal e As EventArgs)
        'Popup result is the selected date
        PopupControlExtender1.Commit(Calendar1.SelectedDate.ToString(_
            mSelectedDateFormat, _
            New System.Globalization.CultureInfo(mCulture)))
    End Sub

    Private Sub SelectCalendar()
        If ddlYear.SelectedValue <> "" Then
            Calendar1.VisibleDate = 
               DateTime.Parse(ddlMonth.SelectedValue & "/" & _
               Day(DateTime.Now()) & "/" & ddlYear.SelectedValue)
        End If

    End Sub

    Protected Sub ddlMonth_SelectedIndexChanged(ByVal sender As Object, _
        ByVal e As System.EventArgs)
        SelectCalendar()
    End Sub

    Protected Sub ddlYear_SelectedIndexChanged(ByVal sender As Object, _
        ByVal e As System.EventArgs)
        SelectCalendar()
    End Sub

    Protected Sub Page_Init(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Me.Init
        If Not IsPostBack Then
            Dim mIndex As Integer
            For mIndex = mYearMinimum To mYearMaximum
                ddlYear.Items.Add(New ListItem(mIndex.ToString(), _
                mIndex.ToString()))
            Next
            ddlYear.SelectedValue = Year(DateTime.Now())
            ddlMonth.SelectedValue = Month(DateTime.Now())
            lbtnClearDate.Visible = mNullable
        End If
    End Sub

    Protected Sub lbtnClearDate_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles lbtnClearDate.Click
        DateTextBox.Text = ""
        PopupControlExtender1.Commit("")
    End Sub

    Protected Sub lbtnToday_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles lbtnToday.Click
        ddlYear.SelectedValue = Year(DateTime.Now())
        ddlMonth.SelectedValue = Month(DateTime.Now())
        SelectCalendar()
        Calendar1.SelectedDate = DateTime.Now()
        PopupControlExtender1.Commit(Calendar1.SelectedDate.ToString(_
            mSelectedDateFormat, _
            New System.Globalization.CultureInfo(mCulture)))
    End Sub

#End Region
End Class

Remember

Check that you have AJAX Extensions and AJAX Control Toolkit installed from the official website.

History

  • 13 August, 2007 -- Original version posted

License

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

About the Author

Ather Ali Shaikh

Software Developer (Senior)
GASCO
United Arab Emirates United Arab Emirates

Member

In Professional since 1997, works on Win32, C#, and .NET technology, ColdFusion is also part of my skill set. expert int MVC design pattern. use Oracle, SQL server 2000/2005 as databases.
Working on SQL Server 2005 Reporting Services
Also works on Oracle 10g database and Oracle R12 Application, customization of forms and reports
you can contact me on:
shaikhather@gmail.com

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. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralPROBLEM RUNNING THE SMPLE Pinmemberlafcadio_ro1:56 5 Nov '08  
GeneralRe: PROBLEM RUNNING THE SMPLE PinmemberAther Ali Shaikh6:15 7 Nov '08  
GeneralRe: PROBLEM RUNNING THE SMPLE Pinmemberlafcadio_ro0:34 12 Nov '08  
GeneralServer side postback! PinmemberJasonC725:15 13 Oct '08  
GeneralMonth & Year can not be changed by dropdowns Pinmemberarpitk0:24 2 Jul '08  
GeneralGetting Error Ajaxtoolkit is undefined PinmemberExelioindia0:45 16 May '08  
Hi,
 
I am trying to use the ajaxToolkit:CalendarExtender in my page named as edit.aspx, it work fine if edit.aspx pages dont have any user controls. If i use a user control in my page then i am getting a javascript error "Ajaxtoolkit is undefined" and the calender is not working. I dnt use any javascript or any Ajax control in that user control.
 
MY code:
 
<![CDATA[<%@ Page Language="C#" MasterPageFile="~/Default.Master" AutoEventWireup="true" CodeBehind="Edit.aspx.cs" Inherits="blog.Admin.UI.comment.Edit" Title="blog Admin" %>]]>
<![CDATA[<%@ Register TagPrefix="uc" Namespace="my.Web.Controls" Assembly="my.Web" %>]]>
<![CDATA[<%@ Register src="../Controls/commentsTopControl.ascx" tagname="commentsControl" tagprefix="uc1" %>]]>
<![CDATA[<%@ Register src="../Controls/EditMenuControl.ascx" tagname="EditMenuControl" tagprefix="uc2" %>]]>
 
<asp:content id="Content1" contentplaceholderid="ContentPlaceHolder1" runat="server">
<ajaxtoolkit:toolkitscriptmanager runat="server">
EnablePartialRendering="true" ID="ScriptManager1"
EnableScriptGlobalization="true"
EnableScriptLocalization="true" />
<uc2:editmenucontrol id="EditMenuControl1" runat="server" />
<uc1:estatetopcontrol id="estateTopControl" runat="server" />
 




 
<asp:checkbox id="ActiveCheckBox" runat="server" text="Visible" />

 
<asp:checkbox id="PostCheckBox" runat="server" text="Posted" />
PostDate<asp:textbox id="PostDateTextBox" runat="server" />
<ajaxtoolkit:calendarextender id="PostDateTextbox_Extender" runat="server" enabled="true" targetcontrolid="PostDateTextBox" format="dd.MM.yyyy">

<asp:button id="saveButton" runat="server" text="Save" cssclass="button" />


 
Know is Drop, Unknown is Ocean

GeneralThanks for your effort -- C# Pinmemberyasso779:41 10 Mar '08  
GeneralNice component Pinmemberluciano_arias7:08 18 Oct '07  
AnswerRe: Nice component PinmemberAther Ali Shaikh22:36 19 Oct '07  

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120604.1 | Last Updated 13 Aug 2007
Article Copyright 2007 by Ather Ali Shaikh
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid