SelectedDate of ASP.NET Calendar control

During years of ASP.NET development, sometimes I find I ignored important page lifecycle even I used some features frequently.

Here is an example of Calendar control. I put the Calendar control dynamically into one page, and put data binding logic for the selected date in Page_Load() like below:

protected new void Page_Load(object sender, EventArgs e)
{
// Call base method
base.Page_Load(sender, e);

// Get selected date
DateTime selectedDate = wsCalendar.SelectedDate;

// Bind data
BindEventList(selectedDate);
}

When I ran the program and check the selectedDate variable, you know what? On the first time postback, the value of selectedDate was 1/1/0001 while I had selected 4/17. On the second time of postback, the value of selectedDate was 4/17, instead of the latest selected date 4/20: I got the selected date of the last time, not the current one!

That result amused me for a while until I realized I made this mistake: I should get the selectedDate in Selectionchanged event. During Page_Load(), the real selectedDate has not been updated yet although part of postBack logic was already executed before load event.

protected void DateChanged(object s, EventArgs e)
{
// I can get the real selected date now
DateTime selectedDate = wsCalendar.SelectedDate;

// Bind data
BindEventList(selectedDate);
}

0 comments: