As example, we are going to create an asp:Calendar control that let us select a day, a week, or an entire month.
Here is the snippet from the changed code in the HTML-body-form section:
<asp:Calendar id="myCalendar" runat="server"
OnSelectionChanged="newDateSelection"
SelectionMode="DayWeekMonth" />
<asp:Label id="myDay" runat="server" />
<p><button id="myReset" onserverclick="resetData"
runat="server">Reset</button></p>
We have created an asp:Calendar with the aforementioned selection mode and the specification to call a method called newDateSelection() when the event selectionChange occurs.
We also have an asp:Label myDay that is going to show to the user the current selection.
And finally we have an HTML button, myReset, that we plan to use to clear the selection in the calendar. To get this task done, it calls the method resetData(), that we are about to write.
Here is the associated C# code:
protected void Page_Load(Object s, EventArgs e) // 1.
{
myCalendar.SelectedDate = myCalendar.TodaysDate;
newDateSelection(s, e);
}
void resetData(Object s, EventArgs e) // 2.
{
System.Diagnostics.Debug.WriteLine("resetData()");
myCalendar.SelectedDate = new DateTime();
newDateSelection(s, e);
}
void newDateSelection(Object s, EventArgs e) // 3.
{
myDay.Text = "";
switch(myCalendar.SelectedDates.Count)
{
case 0:
myDay.Text = "No date selected";
break;
case 1:
myDay.Text = myCalendar.SelectedDate.ToShortDateString();
break;
default:
myDay.Text = "From " + myCalendar.SelectedDates[0].ToShortDateString();
myDay.Text += " to " +
myCalendar.SelectedDates[myCalendar.SelectedDates.Count-1].ToShortDateString();
break;
}
myDay.Text += "<br />";
}
1. We want to do some setting up on the calendar control. A good place to do that is when the page is loaded, so we change the Page_Load() method. The setup is actually about selecting the current day in the calendar. Here we change the SelectedDate property for our calendar, setting it to the TodayDate (again a property for the calendar object itself), then we delegate to another method of ours, newDateSelection(), the job of displaying to the user what we have done.
2. This is the method called when we push the reset button. Its first line is there almost just to show how to add some debug message to our code. The second line does the dirty job of creating a new DataTime object with no parameter - the result is what is (usually) considered a fake date, that in this context means no data selected. And finally we call newDateSelection().
3. This method takes care of displaying to the user the date(s) currently selected in the calendar, putting the result in the asp:Label myDay. If we have selected an interval of dates, we show just the first and the last day.
No comments:
Post a Comment