How to show and select month/year in Calendar Extender
In this post I will explain you, How to make calendar extender control to show month / year view by default and instead of selecting dates how can we use calendar extender to select months.
Before I start, let me say that I got extensive support from this forum post http://forums.asp.net/t/1349086.aspx. Thanks to Zhi-Qiang Ni, but the way he follow was a little bit lengthy. However, all credit still goes to him because I gain the exact idea from his post.
Let me start by creating a calendar extender control and attach it to a textbox.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" OnClientHidden="onCalendarHidden" OnClientShown="onCalendarShown" BehaviorID="calendar1"
Enabled="True" TargetControlID="TextBox1">
</cc1:CalendarExtender>
Now, in extender markup, notice onClientHidden and OnClientShown event which I implemented as below.
function onCalendarShown() {
var cal = $find("calendar1");
//Setting the default mode to month
cal._switchMode("months", true);
//Iterate every month Item and attach click event to it
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", call);
}
}
}
}
function onCalendarHidden()
{
var cal = $find("calendar1");
//Iterate every month Item and remove click event from it
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",call);
}
}
}
}
Pretty simple, In onCalendarShown method I just set the default mode to month and then iterate the control to get month item and attach on click event to it. So that, it will not go further to show us dates of that month and select the first day of that month instead.
Where as, In onCalendarHidden I am simply detaching the click event from month items. Now notice the last parameter of Sys.UI.DomEvent.addHandler function, it is the name of the function which will do the rest of the magic as below.
function call(eventElement)
{
var target = eventElement.target;
switch (target.mode) {
case "month":
var cal = $find("calendar1");
cal._visibleDate = target.date;
cal.set_selectedDate(target.date);
cal._switchMonth(target.date);
cal._blur.post(true);
cal.raiseDateSelectionChanged();
break;
}
}
Here we are simply selecting the month as the selected date of calendar control. and finally the control will look like as below.
You can get the source code from here :
http://cid-cdbfe38dc780f729.skydrive.live.com/self.aspx/.Public/Calendar%20Extender%20Month.zip