User-219423983 posted
Hi Yeoman,
I made a demo based on your description as the following codes. I show the "current" month on a label, it would be changed when visible month changed. The
Calendar1.VisibleDate gets or sets the DateTime value that specifies the month to display on the Calendar control, you could use this property to get the "current" month.
As you use a web user control, the month changed event always occurs after the main page loads. The cookie would be a wise choose that created on client and we can get the value immediately. The following demo provides you a method to get the “current”
month, I think it would be useful to you. Because I don’t clear your page implementation, I couldn’t make sure why the problem described above happened. You could provide more information about the code.
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CalendarUC.ascx.cs" Inherits="DailyThreads.CSharp.UserControl.CalendarUC" %>
<asp:Calendar ID="Calendar1" runat="server" onclick="getCurrentMonth();" NextMonthText="&gt;&gt;" PrevMonthText="&lt;&lt;" OnSelectionChanged="Calendar1_SelectionChanged" OnVisibleMonthChanged="Calendar1_VisibleMonthChanged"></asp:Calendar>
Current Month:<asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
Selected Date:<asp:Label ID="Label2" runat="server" Text=""></asp:Label>
<script type="text/javascript">
function getCurrentMonth()
{
var aobject= document.activeElement.title;
var ispostback= <%= Convert.ToInt32(IsPostBack)%>;
var currentShownMonth;
if(ispostback==0)
{
currentShownMonth = <%= DateTime.Now.Month%>;
}
else{
currentShownMonth = <%= Calendar1.VisibleDate.Month%>;
}
if(aobject.toString().toLowerCase().indexOf("next")>0)
{
currentShownMonth = (currentShownMonth+1)>12?1:(currentShownMonth+1);
}
if(aobject.toString().toLowerCase().indexOf("previous")>0)
{
currentShownMonth = (currentShownMonth-1)<1?12:(currentShownMonth-1);
}
var calcontro = document.getElementById('<%= Calendar1.ClientID%>');
var expdate = new Date();
expdate.setTime(expdate.getTime() + 30 * 60 * 1000);
document.cookie="CurrentShownMonth"+"="+escape(currentShownMonth)+";expires=" + expdate.toGMTString();
}
</script>
The .cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.Label1.Text = DateTime.Now.Month.ToString();
}
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
this.Label2.Text ="SelectedDay:" + this.Calendar1.SelectedDate.Day.ToString() + "; SelectedMonth:" + this.Calendar1.SelectedDate.Month.ToString();
}
protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
{
this.Label1.Text =this.Calendar1.VisibleDate.Month.ToString();
}
I hope it’s useful to you.
Best Regards,
Weibo Zhang