Calendar Web 控件所支持的事件分别为OnDayRender、OnVisibleMonthChanged 以及OnSelectionChanged 这三个事件,接下来我们来了解如何使用。
OnSelectionChanged 事件
OnSelectionChanged 事件当使用者点选月历控件上的不同日期,或选了整月或整周时触发。其宣告语法为:
Sub OnSelectionChanged(Sender As Object, e As EventAres)
...
End Sub
下列范例显示使用者所点选的日期:
<Html>
<Form runat="Server">
<ASP:Calendar Id="calA" Runat="Server"
SelectionMode="DayWeekMonth" ShowGridLines="True"
ShowNextPrevMonth="True" NextMonthText="[Next]"
SelectedDayStyle-BackColor="#DBDBDB"
OnSelectionChanged="calA_SC"/>
</Form>
<ASP:Label Id="Label1" Runat="Server"/>
<Script Language="VB" Runat="Server">
Sub calA_SC(Sender As Object, e As EventArgs)
Label1.Text="您所点选的日期为: " & calA.SelectedDate
End Sub
</Script>
</Html>
上述范例当使用者选取整周或整个月时,只能显示所选取的第一天;若要显示被选取的范围,利用SelectedDates 集合来取得使用者点选的范围。下列范例可以显示使用者选取的整周或整月:
<Html>
<Form runat="Server">
<ASP:Calendar Id="calA" Runat="Server"
SelectionMode="DayWeekMonth" ShowGridLines="True"
ShowNextPrevMonth="True" NextMonthText="[Next]"
SelectedDayStyle-BackColor="#DBDBDB"
OnSelectionChanged="calA_SC"/>
</Form>
<ASP:Label Id="Label1" Runat="Server"/>
<Script Language="VB" Runat="Server">
Sub calA_SC(Sender As Object, e As EventArgs)
Label1.Text="您所点选的日期为: " & calA.SelectedDate
If calA.SelectedDates.Count > 1 Then
Label1.Text + = " 至" &
calA.SelectedDates.Item(calA.SelectedDates.Count-1)
End If
End Sub
</Script>
</Html>
由于SelectedDates 是集合对象,我们当然可以加入一些特定的日期到集合中,只要利用SelectedDates.Add 方法即可。另外SelectedDates 集合中有SelectRange 属性可以用来指定某个范围的日期。下列范例让使用者输入指定范围的日期,然后利用Calendar Web 控件显示:
<Html>
<Form runat="Server">
请输入日期范围(格式YYYY/MM/DD):<br>
从: <ASP:TextBox Id="Text1" Runat="Server"/>
至: <ASP:TextBox Id="Text2" Runat="Server"/>
<ASP:Button Id="btnOK" Text="确定" OnClick="btnOK_Click"
Runat="Server"/><br>
<ASP:Calendar Id="calA" Runat="Server"
SelectionMode="DayWeekMonth" ShowGridLines="True"
ShowNextPrevMonth="True" NextMonthText="[Next]"
SelectedDayStyle-BackColor="#DBDBDB"/>
</Form>
<Script Language="VB" Runat="Server">
Sub btnOK_Click(Sender As Object, e As EventArgs)
calA.SelectedDates.SelectRange(Text1.Text, Text2.Text)
End Sub
</Script>
</Html>
OnVisibleMonthChanged 事件
OnVisibleMonthChanged 事件当使用者点选月历控件标题列上的上个月或下个月按钮时触发。其宣告语法为:
Sub OnVisibleMonthChanged(Sender As Object, e As MonthChangedEventArgs)
...
End Sub>
其中参数e 有两个属性,如下表所示:
OnDayRender 事件
OnDayRender 事件当月历控件在产生每一天的表格时触发。其宣告语法为:
Sub OnDayRender(Sender As Object, e As DayRenderEventArgs)
...
End Sub
其中参数e 有14 个属性,如下表所示:
下列范例单纯的显示月历,并将本月的双数日期反像显示:
<%@Import Namespace="System.Drawing"%>
<Html>
<Form runat="Server">
<ASP:Calendar Id="calA" Runat="Server"
SelectionMode="None" ShowGridLines="True"
BorderColor="Gray" TitleStyle-BackColor="White"
OnDayRender="calA_DayRender"/>
</Form>
<Script Language="VB" Runat="Server">
Sub calA_DayRender(Sender As Object, e As DayRenderEventArgs)
If e.Day.DayNumberText.ToInt16 Mod 2 = 0 And Not e.Day.IsOtherMonth
Then
e.Cell.BackColor=Color.Gray '以颜色名称设定颜色
e.Cell.ForeColor=Color.FromARGB(255,255,255,255) '设定颜色
End If
End Sub
</Script>
</Html>