用戶控件標記
<%@ Control Language="c#" AutoEventWireup="false" Codebehind="ctlCalendar.ascx.cs"
Inherits="calendar.ctlCalendar" TargetSchema="https://schemas.microsoft.com/intellisense/ie5" %>
<asp:TextBox ID="TextBox1" runat="server" />
<input type="button" id="Button1" runat="server" value="..." /><br>
<asp:Panel ID="pnlCalendar" runat="server" style="POSITION: absolute; DISPLAY: none;">
<asp:Calendar ID="Calendar1" runat="server" FirstDayOfWeek="Monday" ShowGridLines="True"
BackColor="White" DayNameFormat="Full" ForeColor="Black" Font-Size="8pt" Font-Names="Verdana"
BorderColor="#999999" CellPadding="4" Width="200px" Height="180px">
<TodayDayStyle ForeColor="Black" BackColor="#CCCCCC" />
<SelectorStyle BackColor="#CCCCCC" />
<DayStyle Wrap="False" BorderStyle="Dashed" />
<NextPrevStyle VerticalAlign="Bottom" />
<DayHeaderStyle Font-Size="X-Small" Font-Names="宋體" Wrap="False" BorderStyle="Dashed" BackColor="#CCCCCC" />
<SelectedDayStyle Font-Bold="True" ForeColor="White" BackColor="#666666" />
<TitleStyle Font-Size="Small" Font-Bold="True" BorderStyle="Solid" BorderColor="Black" BackColor="#999999" />
<WeekendDayStyle BackColor="LightSteelBlue" />
<OtherMonthDayStyle ForeColor="Gray" />
</asp:Calendar>
</asp:Panel>
後台代碼
using System;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace calendar
{
public class ctlCalendar : System.Web.UI.UserControl
{
protected TextBox TextBox1;
protected Panel pnlCalendar;
protected HtmlInputButton Button1;
protected Calendar Calendar1;
private void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TextBox1.Text = DateTime.Now.ToShortDateString();
pnlCalendar.Attributes["style"] = "DISPLAY: none; POSITION: absolute";
}
else
{
// 點擊頁面其他區域關閉日曆
string targetId = Page.Request.Form["__EVENTTARGET"]?.Split(':')[0];
if (targetId != this.ID)
pnlCalendar.Attributes["style"] = "DISPLAY: none; POSITION: absolute";
else
pnlCalendar.Attributes["style"] = "POSITION: absolute";
}
// 註冊客戶端切換顯示腳本
string script = $@"
function On{this.ID}Click() {{
var p = document.getElementById('{pnlCalendar.ClientID}');
p.style.display = (p.style.display == 'none') ? '' : 'none';
}}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Script_Panel" + this.ID, script, true);
Button1.Attributes["onclick"] = "On" + this.ID + "Click()";
}
private void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox1.Text = Calendar1.SelectedDate.ToShortDateString();
pnlCalendar.Attributes["style"] = "DISPLAY: none; POSITION: absolute";
}
protected override void OnInit(EventArgs e)
{
Calendar1.SelectionChanged += Calendar1_SelectionChanged;
Load += Page_Load;
base.OnInit(e);
}
}
}
使用方式
<%@ Register TagPrefix="uc" TagName="Calendar" Src="~/ctlCalendar.ascx" %>
...
<uc:Calendar ID="MyCalendar" runat="server" />
// 取值:MyCalendar.TextBox1.Text
現代替代方案