.net基础扫盲-属于自己自定义控件

  一个简单的自定义控件此控件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>标记具体指示控件的位置,以及属性设置等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值