2011年7月14日 星期四

ASP.NET自訂控制項 - 簡單的日期選擇輸入框 DateBox

有了AjaxToolkit之後,應該就可以很容易的使用CalendarExtender與TextBox來達到日期選擇的功能,不過仍然需要花費一點時間在CalendarExtender控制項上的設定,其實透過一些簡單的程式碼包裝成Server Control就可以很容易的使用這樣的功能.

1.先來看看整合的效果與使用方式
ASPX

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager ID="scriptManager1" runat="server" />

<Demo:DateBox ID="DateBox1" runat="server"
ImageUrl="~/Images/DateBox.gif" Format="yyyy/MM/dd" /><br/>

<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" /><br/>

Date: <asp:Label ID="lblDate" Font-Bold="true" runat="server" /><br/>
DateText: <asp:Label ID="lblDateText" Font-Bold="true" runat="server" />
</form>
</body>
</html>

C#

namespace Likol.Web.DemoWebSite
{
public partial class DateBox : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnSubmit_Click(object sender, EventArgs e)
{
this.lblDate.Text = this.DateBox1.Date.ToString("yyyy/MM/dd");
this.lblDateText.Text = this.DateBox1.DateText;
}
}
}

我們可以透過兩個屬性Date(DateTime), DateText(string)來取得輸入資料.

日期選擇輸入框 DateBox Demo
http://www.aspcity.idv.tw/DateBox.aspx

雖然在這個範例中似乎沒有帶來相當大的便利性,可是對程式設計師來說能少一個步驟就少一個步驟,能把更多的時間花費在重要的程式碼上,其實才是重要的.

DateBox.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;

namespace Likol.Web.DemoWebSite.WebControls
{
[
ToolboxData("<{0}:DateBox runat=server>")
]
public class DateBox : CompositeControl
{
private TextBox txtValue;
private ImageButton ibButton;
private CalendarExtender ceCalendar;

public string ImageUrl
{
get
{
object value = this.ViewState["ImageUrl"];

if (value == null) return "";

return (string)value;
}
set { this.ViewState["ImageUrl"] = value; }
}

public string Format
{
get
{
object value = this.ViewState["Format"];

if (value == null) return "";

return (string)value;
}
set { this.ViewState["Format"] = value; }
}

public string DateText
{
get
{
this.EnsureChildControls();

return this.txtValue.Text;
}
set
{
this.EnsureChildControls();

this.txtValue.Text = value;
}
}

public DateTime Date
{
get { return Convert.ToDateTime(this.DateText); }
set { this.DateText = value.ToString(this.Format); }
}

protected override void CreateChildControls()
{
this.txtValue = new TextBox();
this.txtValue.ID = "Value";
this.txtValue.MaxLength = 10;

this.ibButton = new ImageButton();
this.ibButton.ID = "Button";
this.ibButton.ImageUrl = this.ImageUrl;

this.ceCalendar = new CalendarExtender();
this.ceCalendar.ID = "Calendar";
this.ceCalendar.TargetControlID = this.txtValue.ID;
this.ceCalendar.PopupButtonID = this.ibButton.ID;
this.ceCalendar.Format = this.Format;

this.Controls.Add(this.txtValue);
this.Controls.Add(this.ibButton);
this.Controls.Add(this.ceCalendar);
}
}
}


Updated: ASP.NET自訂控制項 - 簡單的日期選擇輸入框 DateBox (二)

沒有留言:

張貼留言