advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Average Rating: 3.2/5 | Rate this item | 5 users have rated this item.
Tip formerly from VB2TheMax
Expertise: Advanced
Language: VB7
February 10, 2003
Creating a popup calendar control
Many data entry forms have one or more text fields that the user should fill with a date value. Many sites have a button near these fields that when clicked pops up a new small window with a calendar, to help the user select the date. When the user clicks on a day (rendered as a hyperlink), this popup calendar window is closed and the selected date is shown in the input textbox control of the parent window. This feature can be easily reproduced in ASP.NET by using the Calendar control and a bit of client-side javascript code.

First of all, let's write the parent window's ASPX code. All we need is the input TextBox server control and a HTML button:


<asp:TextBox id="DateTextBox" runat="server" />
<INPUT type="button" value="Pick"
    onclick="PopupPicker('DateTextBox', 250, 250);">
As you see, when the button is pressed it calls a javascript procedure that expects in input the name of the textbox control that will be filled with the selected date, and the width and height of the popup calendar window that will be opened. Here's the javascript code, defined within the page's <HEAD> section:

<script language=javascript>
    function PopupPicker(ctl,w,h)
    {
        var PopupWindow=null;
        settings='width='+ w + ',height='+ h + ',location=no,directories=no,
                 ' menubar=no,toolbar=no,status=no,scrollbars=no,resizable=no,
                 ' dependent=no';
        PopupWindow=window.open('DatePicker.aspx?Ctl=' + ctl,'DatePicker',
                                ' settings);
        PopupWindow.focus();
    }
</script>
The procedure above uses window.open to open the popup window with the specified size, and with no scrollbar, menu, toolbar, status bar, and makes it not resizable. The first parameter is the Url of the page to load into the new window, and from the code above you see that it loads a DatePicker.aspx page with a Ctl parameter in the querystring, whose value is that passed in input to the PopupPicker procedure.

We're done with the main page, now we have to write the DatePicker.aspx page, that renders the calendar. Let's see the code first:


<%@ Page Language="vb" AutoEventWireup="false" Codebehind="DatePicker.aspx.vb" _
    Inherits="FrameTest.DatePickerPage"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
  <HEAD>
    <title>DatePicker</title>   
    <script language="Javascript" >
        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();
        }
    </script>
</HEAD>
  <body leftmargin="0" rightmargin="0" topmargin="0" bottommargin="0" _
      marginwidth="0" marginheight="0">
    <form id="Form1" method="post" runat="server">
        <asp:Calendar runat="server" id="DatePicker" Width="100%" Height="100%" _
            />
    </form>
  </body>
</HTML>
In the <BODY> section we just declare an instance of the server-side Calendar control. The interesting part is above, the client-side SetDate javascript procedure, that takes a string in input, and uses it as value for the parent form's input control, whose name is passed on the querystring. Finally, it closes the popup form itself. The provided comments should make clear how the input control name is retrieved from the querystring.

What we want to do now is that this javascript procedure is called when the user clicks a day link in the calendar control. By default, all the links rendered by the Calendar server control generate a postback to the server. What we want, instead, is that they point to our custom SetDate procedure. Changing the default output for the table cells that contains the day links is pretty easy, thanks to the Calendar's DayRender event, raised every time a day is being rendered, and that provides a reference to the table cell being created. What we do in the code below is replacing the default cell's content with our own hyperlink control that has the same text but points to our own javascript:


Public Class DatePickerPage
    Inherits System.Web.UI.Page
    Protected WithEvents DatePicker As System.Web.UI.WebControls.Calendar

    Private Sub DatePicker_DayRender(ByVal sender As Object, _
        ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles _
        DatePicker.DayRender
        ' create a hyperlink control, and set its text to the cell's current 
        ' text
        Dim hl As New HyperLink()
        hl.Text = CType(e.Cell.Controls(0), LiteralControl).Text
        ' set the navigation url (the href attribute) to the javascript 
        ' procedure
        ' defined wihin the client-side <script> block, and pass in input
        ' the clicked date in short format
        hl.NavigateUrl = "javascript:SetDate('" & e.Day.Date.ToShortDateString() _
            & "');"
        ' remove the cell's current child controls, and add the new hyperlink
        e.Cell.Controls.Clear()
        e.Cell.Controls.Add(hl)
    End Sub
End Class
The value passed in input to the javascript procedure is the date of the clicked day, in short format (typically MM/dd/yy), that's the value that will be used for the input control on the parent form.

Once you understand how all this work, you see that's quite easy actually, the ASP.NET server control are flexible enough to be highly customized! Another occasion where you may want to use the DayRender event in a similar way, is when you want the browser to be redirected to another page with the selected date passed on the querystring, instead of using the standard behavior to redirect to the second page from the server, after a postback of the first form. To do this, just replace the line where you set the hyperlink's NavigateUrl property, with something similar to the following:


hl.NavigateUrl = "SecondPage.aspx?Date=" & e.Day.Date.ToShortDateString()
Marco Bellinaso
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.
advertisement
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES