ASP控制項內建的Calendar在美觀上不賴,但日期卻不太方便!
之前又常在別人的網站裡,看到用DropDownList來做挑選日期的控制項。
於是就著手來試一個,藉由幾個控制項就可以達成!
環境:VS2012
1. .aspx的Form內容
其中使用UpdatePanel(因此需要ScriptManager),受限於Panel自動換行,使用Table tag來做處理
<asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
<table>
<tr>
<td>
<asp:UpdatePanel ID="up_month" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<asp:DropDownList ID="ddl_month" DataTextField="monthText" DataValueField="monthValue" OnSelectedIndexChanged="ddl_month_SelectedIndexChanged" AutoPostBack="true" runat="server"></asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</td>
<td>
<asp:UpdatePanel ID="up_day" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="ddl_day" runat="server" ></asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddl_month" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</td>
<td>
<asp:DropDownList ID="ddl_year" runat="server"></asp:DropDownList>
</td>
</tr>
</table>
2. Code Behide
為了使用DateTimeFormatInfo,請先引用:
using System.Globalization;
剩餘的是設定DDL的內容的程式碼
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Populate DropDownLists
ddlMonth.DataSource = Enumerable.Range(1, 12).Select(a => new
{
MonthName = DateTimeFormatInfo.CurrentInfo.GetMonthName(a),
MonthNumber = a
});
ddlMonth.DataBind();
ddlYear.DataSource = Enumerable.Range(DateTime.Now.Year - 99, 100).Reverse();
ddlYear.DataBind();
ddlday.DataSource = Enumerable.Range(1, DateTime.DaysInMonth(DateTime.Now.Year, Convert.ToInt32(ddlMonth.SelectedValue)));
ddlday.DataBind();
}
}
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
ddlday.DataSource = Enumerable.Range(1, DateTime.DaysInMonth(DateTime.Now.Year, Convert.ToInt32(ddlMonth.SelectedValue)));
ddlday.DataBind();
}
參考資料:
UpdatePanel 更新的程式化控制-明確的 update 方法呼叫
使用 UpdatePanel 實現 DropdownList 不刷新連動,包含設置與使用方法
請先 登入 以發表留言。