I'm adding a Calendar to to my application and am having a hard time updating the date. For some reason when I select a new date the previous date is displayed. So if it starts on the 11th and I select the 13th, the 11开发者_如何学Cth is displayed again when the page reloads and then if I select the 14th after that the 13th will load.
I declare the calendar in the application like this:
<asp:Calendar ID="myCal" runat="server"></asp:Calendar>
And then I have this code in page_init:
myCal.SelectedDate = DateTime.Today.AddDays(1);
And use this in page_load:
String date = myCal.SelectedDate.ToString("yyyyMMdd");
Thanks.
Your calendar probably triggers a postback, but the Page_Load
event occurs before any control events. That means you are loading the "previous" selected value each time in the Page_Load
method.
You should move your string date = myCal.SelectedDate.ToString("yyyyMMdd");
and its associated usage from the Page_Load
to the SelectionChanged
event handler for the calendar control.
So create the following method:
protected void myCal_SelectionChanged(Object sender, EventArgs e)
{
string date = myCal.SelectedDate.ToString("yyyyMMdd");
// lblMyLabel.Text = date;
// Put your code that handles the selected date here.
}
And associate it with your calendar:
<asp:Calendar ID="myCal" runat="server"
OnSelectionChanged="myCal_SelectionChanged"></asp:Calendar>
精彩评论