How To Create a Pop-Up Calendar User Web Control
By Sean Kramer
Published: 4/9/2002
Reader Level: Beginner
Rated: 4.75 by 4 member(s).
Tell a Friend
Rate this Article
Printable Version
Discuss in the Forums

This How To will demonstrate the creation of a pop-up calendar user control and also provide an example of how to use the control. Anyone who has had to include a pop-up calendar on a web form in classic ASP has probably experienced the massive amount of Javascript needed to create such a thing. In .NET this is greatly simplified. .NET comes with its own easy to use calender server control.

In this How To we will be utilizing the calendar and panel server controls that are native to .NET. The panel control is used to give the calendar a floating effect on the page. By placing the calendar control within the panel control, you can easily reposition the calendar as well as hide and show the calendar based on user's selections. In order to make this pop-up calendar easier to use as well as reusable, we will make our pop-up calendar into a user control. This way we can include the user control in any project and easily add it to any form we wish.

Figure 1 below shows what the example page that we will create looks like and the pop-up calendar in action.

Figure 1

Creating the User Class

The first thing that needs to be done is to create a class file that will contain the panel and calendar server controls. The following file, popUpCalendar.ascx, does just that.

[popUpCalendar.ascx]
<%@ Control Language="vb" AutoEventWireup="false" Codebehind="popUpCalendar.ascx.vb" Inherits="CalendarExample.popUpCalendar" %>

<asp:panel id="pnlCalendar" style="Z-INDEX: 101; LEFT: 0px; POSITION: absolute; TOP: 0px" runat="server" Height="86px" Width="145px">

  <asp:Calendar id="Calendar1" runat="server" Height="86" Width="145"
  BackColor="White" BorderColor="Black" BorderStyle="Solid"
  NextMonthText="<IMG src='monthright.gif' border='0'>"
  PrevMonthText="<IMG src='monthleft.gif' border='0'>">
     <TodayDayStyle BackColor="#FFFFC0"></TodayDayStyle>
     <DayStyle Font-Size="8pt" Font-Names="Arial"></DayStyle>
     <DayHeaderStyle Font-Size="10pt" Font-Underline="True" Font-Names="Arial"
     BorderStyle="None" BackColor="#E0E0E0"></DayHeaderStyle>
     <SelectedDayStyle Font-Size="8pt" Font-Names="Arial" Font-Bold="True"
     ForeColor="White" BackColor="Navy"></SelectedDayStyle>
     <TitleStyle Font-Size="10pt" Font-Names="Arial" Font-Bold="True"
     ForeColor="White" BackColor="Navy"></TitleStyle>
     <OtherMonthDayStyle ForeColor="Gray"></OtherMonthDayStyle>
  </asp:Calendar>

</asp:panel>

The line that starts <asp:panel id="pnlCalendar" .... is what creates the panel server control. You will notice that the calendar server control is placed within the panel control. This way the panel determines the location and visibility of the calendar and will also allow the calendar to "float" on the form. The statement NextMonthText="<IMG src='monthright.gif' border='0'>" tells the calendar control to use the gif image file as the "next month" icon contained on the calendar itself. The same is done for the "previous month" icon.

The next thing that needs to be done is to create the code for the pop-up calendar. The control needs to contain code for hiding and showing the pop-up calendar as well as positioning and setting the appropriate dates. I have provided comments within the code, so I won't explain here too much about what is going on in the code.

There are two items however, that I believe need a little further explanation. The first is the line that reads Calendar1.SelectedDate = #12:00:00 AM#. The value "12:00:00 AM" is the default value of the SelectedDate property. The above line is called when a date is not passed into the function that displays the calendar. By setting the SelectedDate property to "12:00:00 AM", the code is telling the calendar control to not display a selected date. In other words, when the calendar is displayed, no date will be selected.

The other item that needs explanation is the use of the Attributes collection of the Calendar control. The line Calendar1.Attributes.Item("SelectedField") = sDateFieldName is storing the name of the field that the pop-up calendar should write to when the the user selects a date on the calendar. This line is basically creating a custom property called SelectedField for the pop-up calendar. The nice thing about using a custom attribute is that the value will be maintained during postbacks without having to write any other code.

[popUpCalendar.ascx.vb]
Public Class popUpCalendar : Inherits System.Web.UI.UserControl
Protected WithEvents Calendar1 As System.Web.UI.WebControls.Calendar
Protected WithEvents pnlCalendar As System.Web.UI.WebControls.Panel

#Region " Web Form Designer Generated Code "

  'This call is required by the Web Form Designer.
  <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

  End Sub

  Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
    'CODEGEN: This method call is required by the Web Form Designer
    'Do not modify it using the code editor.
    InitializeComponent()
  End Sub

#End Region

Public Sub displayCalendar(ByVal sCalToolText As String, _
ByVal dSelectedDate As Date, _
ByVal sDateFieldName As String, _
ByVal iTop As Integer, _
ByVal iLeft As Integer)
  '************************************************************************
  'Purpose: Displays & hides the calendar.
  'Input: sCalToolText - Text to use as the tooltip text for the calendar
  ' dSelectedDate - Date to set as the selected date for the calendar
  ' txtDate - string containing name of applicable textbox
  ' iTop - top position of calendar
  ' iLeft - left position of calendar
  '************************************************************************

  'If the calendar is visible, but it is displayed for a different field
  'than the one selected, then hide it
  If pnlCalendar.Visible = True And Calendar1.Attributes.Item("selectedfield") <> sDateFieldName Then
     hideCalendar()
  End If

  'If the calendar is hidden, then position it and show it, otherwise hide it
  If pnlCalendar.Visible = False Then

    'Set the location of the calendar
    pnlCalendar.Style.Item("top") = iTop
    pnlCalendar.Style.Item("left") = iLeft

    'If a valid date is passed in, then set this date as the selected date
    'on the calendar. Otherwise display the current month and year

    If IsDate(dSelectedDate) Then
      'Setting the selected date property will tell the calendar to
      'highlight the date assigned to this property.

      Calendar1.SelectedDate = dSelectedDate

      'Setting the visible date property will tell the calendar to
      'initially display the month and year of the date assigned to
      'this property.

      Calendar1.VisibleDate = dSelectedDate
    Else
      Calendar1.SelectedDate = #12:00:00 AM#
      Calendar1.VisibleDate = Now
    End If

    'Set the tooltip text and id of the selected field
    Calendar1.ToolTip = sCalToolText
    Calendar1.Attributes.Item("SelectedField") = sDateFieldName

    'Show the calendar
    pnlCalendar.Visible = True
  Else
    'Hide the calendar
    hideCalendar()
  End If

End Sub

Public Sub Calendar1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Calendar1.SelectionChanged
  '************************************************************************
  'Purpose: Write the selected date to the appropriate text field.
  '************************************************************************
  Dim txtDate As TextBox

  'get the textbox that the date should be written to
  txtDate = Page.FindControl(Calendar1.Attributes.Item("SelectedField"))

  'Write value to appropriate textbox
  txtDate.Text = Calendar1.SelectedDate

  'Hide the calendar
  hideCalendar()

End Sub

Public Sub hideCalendar()
  'Hide the calendar
  pnlCalendar.Visible = False
End Sub
End Class

Creating the Sample Page

Now that we have created a custom user control, we will create a sample web form that uses this control. The following code creates the web form. There are two important lines contained in this code that add our pop-up calendar user control to the web form. The first line <%@ Register TagPrefix="sk" TagName="popUpCalendar" src="/Content/skra87/47062D32-1A67-456A-9E2F-43E7F9D7130F/popupcalendar.ascx""%> makes the control available to the page. The other line <sk:popUpCalendar id="myCalendar" runat="server" /> actually places the user control on the page and gives it an id which we can use to refer to this control in our code. The page also contains two textboxes and two buttons.

[dispCalendar.aspx]
<%@ Register TagPrefix="sk" TagName="popUpCalendar" src="/Content/skra87/47062D32-1A67-456A-9E2F-43E7F9D7130F/popupcalendar.ascx""%>
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="dispCalendar.aspx.vb" Inherits="CalendarExample.dispCalendar" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
  <HEAD>
    <title>dispCalendar</title>
    <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
    <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  </HEAD>
  <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server">

    <sk:popUpCalendar id="myCalendar" runat="server" />

    <H3>Example Use of Custom Calendar Control</H3>
    <table>
      <tr>
        <td width="75">
          Start Date:
        </td>
        <td>
          <asp:TextBox id="txtStartDate" runat="server" Width="86px"></asp:TextBox>
        </td>
        <td>
          <asp:ImageButton id="btnStartDate" runat="server" ImageUrl="calendar.gif"></asp:ImageButton>
        </td>
      </tr>
      <tr>
        <td width="75">
          End Date:
        </td>
        <td>
          <asp:TextBox id="txtEndDate" runat="server" Width="86px"></asp:TextBox>
        </td>
        <td>
          <asp:ImageButton id="btnEndDate" runat="server" ImageUrl="calendar.gif"></asp:ImageButton>
        </td>
      </tr>
    </table>
    </form>
  </body>
</HTML>

Lastly, we will create the code for the form. When the page initially loads, the pop-up calendar will be hidden. When a user clicks on a button, the pop-up calendar will be displayed and positioned next to the button that was selected.

The line that reads Protected WithEvents myCalendar As popUpCalendar allows the code below to reference the pop-up calendar that was created in aspx file above.

[dispCalendar.aspx.vb]
Public Class dispCalendar
  Inherits System.Web.UI.Page
  Protected WithEvents txtStartDate As System.Web.UI.WebControls.TextBox
  Protected WithEvents btnEndDate As System.Web.UI.WebControls.ImageButton
  Protected WithEvents btnStartDate As System.Web.UI.WebControls.ImageButton
  Protected WithEvents txtEndDate As System.Web.UI.WebControls.TextBox
  Protected WithEvents myCalendar As popUpCalendar

#Region " Web Form Designer Generated Code "

  'This call is required by the Web Form Designer.
  <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

  End Sub

  Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
    'CODEGEN: This method call is required by the Web Form Designer
    'Do not modify it using the code editor.
    InitializeComponent()
  End Sub

#End Region

  Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If Not IsPostBack Then
      'Hide the calendar on initial page load
      myCalendar.hideCalendar()
    End If
  End Sub

  Private Sub btnStartDate_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnStartDate.Click
    '************************************************************************
    'Purpose: Check for a valid date in the appropriate text field and call
    'procedure to display calendar.
    '************************************************************************
    Dim dSelDate As Date

    If IsDate(txtStartDate.Text) Then
      dSelDate = txtStartDate.Text
    End If
    myCalendar.displayCalendar("Select a start date", dSelDate, _
      "txtStartDate", 59, 220)

  End Sub

  Private Sub btnEndDate_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnEndDate.Click
    '************************************************************************
    'Purpose: Check for a valid date in the appropriate text field and call
    'procedure to display calendar.
    '************************************************************************
    Dim dSelDate As Date

    If IsDate(txtEndDate.Text) Then
      dSelDate = txtEndDate.Text
    End If
    myCalendar.displayCalendar("Select an end date", dSelDate, _
      "txtEndDate", 86, 220)

  End Sub

End Class

Conclusion

This How To has explained how to create a pop-up calendar user control. Now that you have the basics for creating and using this control, you can customize it to fit the specific needs of your project.



Marketplace
(Sponsored Links)
What are the green links?
   



 
Copyright © 2007 CMP Tech LLC |
Privacy Policy (4/10/06) | Your California Privacy Rights (4/10/06) | Terms of Service | Advertising Info | About Us | Help