Introducing DotNetFunda.com on mobile http://m.dotnetfunda.com ! Be with DotNetFunda.com on the go !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 29843 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET AJAX > Ajax CalendarExtender

Ajax CalendarExtender

Article posted by Pratikshagzb on 8/30/2010 | Views: 30496 | Category: ASP.NET AJAX | Level: Beginner | Points: 150 red flag


CalendarExtender is an ASP.NET AJAX control that is generally used with TextBox control. When user clicks in Textbox, Calendar control Pops up. Here I am discussing various properties of CalendarExtender .

Download


 Download source code for Ajax CalendarExtender


The easiest way for end users is to select a date  from the Calendar which is  on Form. The calendar date can then be translated to a text date format in the TextBox. The CalendarExtender control gives you all the client-side code required for this kind of action. 


ASP.NET Control Toolkit is not part of default install of Visual Studio 2008.You have to  install  ASP.NET Control Toolkit or it can be downloaded from http://ajaxcontroltoolkit.codeplex.com/releases/view/43475.


Some Important  Properties Of CalendarExtender 


Sr No.


Property Name


Description


1


OnClientHidden


Client script that executes  after the calendar is hidden


2


OnClientHiding


Client script that executes  before the calendar is hidden

 


 


3


OnClientShowing


Client script that executes  before the calendar is displayed


4


OnClientShown


Client script that executes immediately after the calendar is displayed.


5


PopUpButtonId


Id of the Button on which the control  will Pop Up.


6


 PopUpPosition


Position where Calendar Control will Pop Up.


7


 SelectedDate


Selected date from  the CalendarExtendar Control and it is only retrievable  through the Target Control or other fields that are manually assigned the value of current selectedDate.


8


 Format


To select only Date and Month  without year “dd/MM”


9


 CssClass


Apply Css to Calendar Extendar Control.


10


OnClientDateSelectionChanged


Script to be run On Date Selection Changed.


11


TargetControlID


Id of the Control to extend with Calendar.


Events


Sr No


Name


Description


1


DataBinding


Occurs when the server control binds to a data source.


2


Disposed


Occurs when a server control is released from memory, which is the last stage of the server control lifecycle when an ASP.NET.


3


Init


Occurs when the server control is initialized, which is the first step in its lifecycle.


4


Load


Occurs when the server control is loaded into the Page object.


5


Pre-Render


Occurs after the Control object is loaded but prior to rendering.


6


ResolveControlID


Called when the ExtenderControlBase fails to locate a control referenced by a TargetControlID. In this event, user code is given opportunity to find the control.


7


Unload


Occurs when the server control is unloaded from memory.



 
Let us discuss some  scenarios in which we apply on the above properties

 

1.  Click on Calendar Icon to make Calender Visible and Click again on Icon to Hide

PopupButtonId Property of CalendarExtendar can be used to Hide and display Calendar on click of Button. 
  

<asp:TextBox ID="txtDate1" runat="server"></asp:TextBox>

<asp:Image ID="Image1" runat="server" Height="19px"

ImageUrl="~/Images/calendar.png.png" />

 

<cc1:CalendarExtender ID="CalendarExtender1" runat="server"

TargetControlID="txtDate1" PopupButtonID="Image1" >

</cc1:CalendarExtender>

2. Format  and Position of CalendarExtendar Control 

To select the Format of the Calendar in which selection is to be made.
Eg. On selecting Date in Calendar  below code will show Date as Wednesday, August 11, 2010 in TextBox .Here Format Property is taken as Format="dddd, MMMM dd, yyyy" . Here PopupPosition Property is shown as Right. It can be selected as Right, Left, Top Right, TopLeft, BottomRight, BottomLeft.

 

<asp:TextBox ID="txtDate2" runat="server"></asp:TextBox> <cc1:CalendarExtender ID="CalendarExtender2" runat="server"

TargetControlID="txtDate2" Format="dddd, MMMM dd, yyyy"  

PopupButtonID="TextBox2" PopupPosition="Right">

</cc1:CalendarExtender>

3.Calendar with Css Styling Applied


Css styling can be applied to Calendar.Calendar background color,Day Name,Month name etc can be changed with Css.Here CssClass is set to cal_Theme1.I have attached a sample css file also in the attached sample.

<asp:TextBox ID="txtDate3" runat="server"></asp:TextBox>

<asp:Image ID="Image2" runat="server" Height="19px"

ImageUrl="~/Images/calendar.png.png" />

<asp:Label ID="Label1" Text ="Theme" runat="server" ></asp:Label>

<cc1:CalendarExtender ID="CalendarExtender3" CssClass="cal_Theme1" runat="server" TargetControlID="txtDate3" Format="dddd, MMMM dd, yyyy"

PopupButtonID="Image2" PopupPosition="Left" >

</cc1:CalendarExtender>

  
 

4.Calender in GridView 


If Calender is to be shown in GridView,use ItemTemplate with TextBox and CalenderExtender in GridView  .Use TargetControlId of the Control in which Calender is to be shown.


<asp:GridView ID="GridView1" runat="server" PageSize="2">

        <Columns>

         <asp:TemplateField>

              <HeaderTemplate>

              <asp:Label Text="Date" runat="server"></asp:Label>

              </HeaderTemplate>

              <ItemTemplate>

              <asp:TextBox ID="TextBox5"  runat="server"></asp:TextBox>

 <cc1:CalendarExtender ID="CalendarExtender4" runat="server" TargetControlID="TextBox5"/>

              </ItemTemplate>

          </asp:TemplateField>              

        </Columns>

</asp:GridView>

 

5. Show Year Navigation


OnClientShown -This Gets or sets the client script that executes immediately after the calendar is displayed.
Here ChangeCalenderView is executed after Calendar is displayed. To show Year Navigation
switch mode in JavaScript as shown in ChangeCalendarView of OnClientShown.

In ChangeCalendarView

sender._switchMode("years", true);

 

<asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>

 <cc1:CalendarExtender ID="CalendarExtender5"  runat="server"     TargetControlID="TextBox6" OnClientShown="ChangeCalendarView" />

6. Show only Day and Month


 <asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>

 <cc1:CalendarExtender ID="CalendarExtender6" Format="dd/MM"

  runat="server" TargetControlID="TextBox7"  />

 

7.  User does not select a Date earlier than today or greater than today.

 

This is done by OnClientDateSelectionChanged  Property. This executes JavaScript function ProperCheckedDate On Date Selection Changed.

           function ProperCheckedDate(sender,args)

        {

             if (sender._selectedDate < new Date())

             {

            alert("Day earler than today cannot be selected.");

             sender._selectedDate = new Date();

                  sender._textbox.set_Value(sender._selectedDate.format(sender._format))

               }

        }

 

<asp:TextBox ID="TextBox9" runat="server"></asp:TextBox>

<cc1:CalendarExtender ID="CalendarExtender7"

runat="server" OnClientDateSelectionChanged=" ProperCheckedDate" TargetControlID="TextBox9" />

 

8. Add Compare and Range  Validation to Calendar Extender control

 

Consider scenarios in which we want to enter only Date in Textbox or we want to enter Date greater than 7 days only and we want to check that proper date is entered .We can use Validators in these cases.
 
To add validation to Calendar add Validator to TextBox. Here CompareValidator is attached to TextBox.


Add an Extender to the ValidationControl. To do so, drag and drop a ValidationControl > click on the smart tag. > Choose ‘Add Extender’. From the Extender Wizard, choose ValidatorCalloutExtender.
Here we have used-


  1. Compare Validator
  2. Range Validator
   1) Compare Validator
Now if 12/34/2010 is entered it will show Invalid Date as Operator is DataTypeCheck and Type=Date.

 

           <asp:TextBox ID="TextBox10" runat="server"></asp:TextBox>

            <asp:CompareValidator ID="CompareValidator1" runat="server" Display="Dynamic"

            ErrorMessage="Invalid Date" Operator="DataTypeCheck" Type="Date"

            ControlToValidate="TextBox10" ></asp:CompareValidator>

        

        <cc1:ValidatorCalloutExtender ID="CompareValidator1_ValidatorCalloutExtender"

            runat="server" Enabled="True" TargetControlID="CompareValidator1">

        </cc1:ValidatorCalloutExtender>

  2) Range Validator

Here Range Validor is used  to show in TextBox.Only  Date greater than 7 days from Current date  can be entered .     

<asp:TextBox ID="TextBox11" runat="server"></asp:TextBox>

       <asp:RangeValidator ID="RangeValidator1" runat="server"

 ControlToValidate="TextBox11" ErrorMessage="Only Date greater then 7          Days from Current Date can be entered." Type="Date">

       </asp:RangeValidator>

<cc1:ValidatorCalloutExtender         ID="RangeValidator1_ValidatorCalloutExtender"

runat="server" Enabled="True" TargetControlID="RangeValidator1">

        </cc1:ValidatorCalloutExtender>

       <cc1:CalendarExtender  ID="CalendarExtender8" runat="server"

            TargetControlID="TextBox11" >

        </cc1:CalendarExtender> 

 

In code behind

RangeValidator1.MinimumValue = System.DateTime.Now.ToShortDateString();

RangeValidator1.MaximumValue = System.DateTime.Now.AddDays(7).ToShortDateString();

   

9. Show and select month/year in Calendar Extender (By using OnClientHidden and OnClientShown


Here I have attached TextBox to CalendarExtender .To show only month in OnClientShown I have set default mode to Month and iterated to attach Click event to it. It will not go further to show us dates of that month and select the first day of that month .


In onCalendarHidden I am removing  the click event from month items. 
By using last parameter of Sys.UI.DomEvent.addHandler function first day of that month is selected.

 

<asp:TextBox ID="TextBox20" runat="server"></asp:TextBox>

    <cc1:CalendarExtender ID="CalendarExtender9" runat="server" OnClientShown="onCalendarShown" OnClientHidden="onCalendarHidden"  BehaviorID="calendar20"

    Enabled="True" TargetControlID="TextBox20">

    </cc1:CalendarExtender>


JavaScript Functions for OnClientShown and OnClientHidden


function onCalendarShown() {

 

     var cal = $find("calendar20");

     //Setting default mode to month

     cal._switchMode("months", true);

    

     //Attach click event

     if (cal._monthsBody) {

         for (var i = 0; i < cal._monthsBody.rows.length; i++) {

             var row = cal._monthsBody.rows[i];

             for (var j = 0; j < row.cells.length; j++) {

                 Sys.UI.DomEvent.addHandler(row.cells[j].firstChild, "click", change);

             }

         }

     }

 }

         

      

       

        function onCalendarHidden()

   {

     var cal = $find("calendar20");

     //Remove click event from every Month

       if (cal._monthsBody)

       {

         for (var i = 0; i < cal._monthsBody.rows.length; i++)

         {

             var row = cal._monthsBody.rows[i];

             for (var j = 0; j < row.cells.length; j++)

              {

                 Sys.UI.DomEvent.removeHandler(row.cells[j].firstChild,"click",change);

              }

         }

     }

   }

  

  

   function change(eventElement)

        {

            var target = eventElement.target;

            switch (target.mode) {

            case "month":

                var cal = $find("calendar20");

                cal._visibleDate = target.date;

                cal.set_selectedDate(target.date);

                cal._switchMonth(target.date);

                cal._blur.post(true);

                cal.raiseDateSelectionChanged();

                break;

            }

        }

 

The Calendar Extendar supports localization ,and you can  localize it by setting the  EnableScriptGlobalization Script Manager property to  true , this way the calendar extendar will display its contents based on the current page culture.

Set Culture   

         <asp:ScriptManager ID="ScriptManager2" runat="server"

         EnableScriptGlobalization="true" EnableScriptLocalization="true"

I have discussed here properties of  CalendarExtender for readers to have good grasp of this control. For reference I have attached sample project also.

All suggestions are welcome.

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:0 year(s)
Home page:
Member since:Friday, March 26, 2010
Level:Starter
Status: [Member]
Biography:
>> Write Response - Respond to this post and get points
Related Posts

In this article explains you how to display an image for textbox server control while on focus the control.

This article describes some ASP.NET Ajax commonly asked questions and answers.

In this article, I am going to show how to maintain browser history in ASP.NET AJAX page while performing asynchronous postback (partial postback).

In this example I create a validation control. It checks if the TextBox is Empty it shows the error message.

Windows applications are more stable than web application. Even if the web is not that stable like a windows application, there are lot advantages of building Web Applications and one thing that we remember as ex-Windows programmers is that the Forms did not Flicker in front of the eyes of the user. This irritates a lot of users. Microsoft came back with a good solution for this problem and they introduced Ajax. In this Article am going to show you how you can create Flicker Free pages.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/28/2012 11:54:33 AM