Click here to Skip to main content
14,302,993 members

DatePicker in ASP.NET 2.0 and AJAX Control Toolkit

Rate this:
3.55 (14 votes)
Please Sign up or sign in to vote.
3.55 (14 votes)
13 Aug 2007CPOL
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)

Share

About the Author

Ather Ali Shaikh
Software Developer (Senior)
United Arab Emirates United Arab Emirates
An ambitious problem solver with a passion for business automation, and who would like to join a team of like-minded professionals. Ather has much experience of creating logical and innovative solutions to complex problems. He is thorough and precise in everything he does, and has a keen interest in technology, web applications and user experience. As someone who takes responsibility for him own personal development, he is continually evaluating and upgrading his skills so that he stays at the cutting edge of web development. He is a natural problem solver, who has proven himself by successfully completing projects for IT consultancies, software houses, web
design agencies, and IT departments.

Comments and Discussions

 
GeneralPROBLEM RUNNING THE SMPLE Pin
lafcadio_ro5-Nov-08 1:56
memberlafcadio_ro5-Nov-08 1:56 
GeneralRe: PROBLEM RUNNING THE SMPLE Pin
Ather Ali Shaikh7-Nov-08 6:15
professionalAther Ali Shaikh7-Nov-08 6:15 
GeneralRe: PROBLEM RUNNING THE SMPLE Pin
lafcadio_ro12-Nov-08 0:34
memberlafcadio_ro12-Nov-08 0:34 
GeneralServer side postback! Pin
JasonC7213-Oct-08 5:15
memberJasonC7213-Oct-08 5:15 
GeneralMonth & Year can not be changed by dropdowns Pin
arpitk2-Jul-08 0:24
memberarpitk2-Jul-08 0:24 
GeneralGetting Error Ajaxtoolkit is undefined Pin
Exelioindia16-May-08 0:45
memberExelioindia16-May-08 0:45 
GeneralThanks for your effort -- C# Pin
yasso7710-Mar-08 9:41
memberyasso7710-Mar-08 9:41 
GeneralNice component Pin
luciano_arias18-Oct-07 7:08
memberluciano_arias18-Oct-07 7:08 
AnswerRe: Nice component Pin
Ather Ali Shaikh19-Oct-07 22:36
professionalAther Ali Shaikh19-Oct-07 22:36 

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

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

Article
Posted 13 Aug 2007

Stats

119.4K views
2.5K downloads
38 bookmarked