一个简单的自定义控件此控件ShowDate控件功能实现显示当前日期标签控件,由System.Web.UI.WebControls.WebControl继承,具有一个custom属性,用于显示问候信息;例如将custom属性值设置为"Ch",则显示结果为"2006年12月30日 星期六 "。ShowDate控件的实现代码包含在ShowDate.cs文件中。该文件源代码如下所示。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ClassLibrary1
{
[DefaultProperty("Custom")]
[ToolboxData("<{0}:WebCustomControl2 runat=server></{0}:WebCustomControl2>")]
public class ShowDate : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("Ch")]
[Localizable(true)]
public string Custom
{
get
{
String s = (String)ViewState["Custom"];
return ((s == null) ? "Ch" : s);
}
set
{
ViewState["Custom"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
string s;
if (Custom.Equals("Ch"))
{
s = DateTime.Now.ToString("D");
string[] x = new string[7] { "日", "一", "二", "三", "四", "五", "六" };
int n;
n = int.Parse(DateTime.Now.DayOfWeek.ToString("D"));
s += " 星期" + x[n] + " " + string.Format("{0:t}", DateTime.Now);
}
else
{
s = string.Format("{0:R}", DateTime.Now);
}
output.Write(s);
}
}
} 在完成项目引用后,Visual Studio 2005将自动在Web站点项目中添加一个Bin文件夹,并在其中包含了ClassLibrary1.dlll和ClassLibrary1.pdb文件。前者是控件程序集,后者中则保存着调试和项目状态信息。这样,Web站点就能够顺利使用HelloMyControl项目的输出了。如下显示了为测试WelcomeLabel控件而创建的Default.aspx文件源代码。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register TagPrefix="self" Namespace="ClassLibrary1" Assembly="ClassLibrary1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>测试自定义控件</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<self:ShowDate ID="WelcomeLabel1" runat="server"></self:ShowDate>
</div>
</form>
</body>
</html>页面利用@ Register指令将ShowDate控件引入,然后,通过<self:ShowDate>标记具体指示控件的位置,以及属性设置等。
本文介绍了一个自定义ASP.NET Web控件ShowDate的实现细节,该控件能够根据设置显示当前日期,支持中文和标准格式。通过示例展示了如何在项目中引用并使用这个控件。
644

被折叠的 条评论
为什么被折叠?



