一、新增使用者控制項。
二、處理程式:
三、如要從物件的SelectDates取出日期陣列,要在PagePrerender中取,因為這時候使用者控制項才會有完整的值。
<%@ Control Language="C#" ClassName="CalendarS" %>
<script runat="server">
//建立型別為DateTime的陣列dates
System.Collections.Generic.List<DateTime>
dates;
//在PageLoad中初始化dates,如果有ViewState["dates"]就用,沒有就new
protected void
Page_Load(object sender,
EventArgs e)
{
if (ViewState["dates"] != null)
dates = (System.Collections.Generic.List<DateTime>)ViewState["dates"];
else
dates = new System.Collections.Generic.List<DateTime>();
}
//日期控制項改變選取日時,就寫入dates中,
//然後將選取日改為Datetime的最小值(配合畫面用)
protected void
Calendar1_SelectionChanged(object sender,
EventArgs e)
{
foreach (DateTime dt in Calendar1.SelectedDates)
{
if (dates.Contains(dt))
dates.Remove(dt);
else
dates.Add(dt);
}
Calendar1.SelectedDate = DateTime.MinValue;
}
//日期控制項繪製時,如為非本月,清除。
//如為今日,設成跟日期控制項的預設底色。(分成周未跟平日)
//如有出現在dates中,設為淺灰色
protected void
Calendar1_DayRender(object sender,
DayRenderEventArgs e)
{
if (e.Day.IsOtherMonth)
{
e.Cell.Controls.Clear();
}
else
{
if (e.Day.Date == DateTime.Today)
if (e.Day.IsWeekend)
e.Cell.BackColor = Calendar1.WeekendDayStyle.BackColor;
else
e.Cell.BackColor = Calendar1.DayStyle.BackColor;
if (dates.Contains(e.Day.Date))
e.Cell.BackColor = System.Drawing.Color.LightGray;
}
}
//在Page_PreRender中,將dates存入ViewState["dates"]
protected void
Page_PreRender(object sender,
EventArgs e)
{
ViewState["dates"] = dates;
}
//設定唯讀的屬性,回傳
日期陣列,接受 日期陣列
public System.Collections.Generic.List<DateTime>
SelectDates
{
get
{
if (ViewState["dates"] != null)
dates = (System.Collections.Generic.List<DateTime>)ViewState["dates"];
else
dates = new System.Collections.Generic.List<DateTime>();
dates.Sort();
return dates;
}
set {
ViewState["dates"] = value; }
}
</script>
<asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_SelectionChanged"
OnDayRender="Calendar1_DayRender" BackColor="White" BorderColor="#999999" CellPadding="4"
DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt" ForeColor="Black"
Height="180px" Width="200px">
<SelectedDayStyle BackColor="#666666" Font-Bold="True" ForeColor="White" />
<SelectorStyle BackColor="#CCCCCC" />
<WeekendDayStyle BackColor="#FFFFCC" />
<TodayDayStyle BackColor="#CCCCCC" ForeColor="Black" />
<OtherMonthDayStyle ForeColor="Gray" />
<NextPrevStyle VerticalAlign="Bottom" />
<DayHeaderStyle BackColor="#CCCCCC" Font-Bold="True" Font-Size="7pt" />
<TitleStyle BackColor="#999999" BorderColor="Black" Font-Bold="True" />
</asp:Calendar>