最近看了msdn关于自定义控件的介绍,根据官方的文档,自己学着做了一个简单的demo给需要的朋友参考。

 

asp.net 源生的textbox是不带label标签的,这里我要实现的是创建一个带label标签的textbox,并且默认填充text值为guid(只读) 

 

实际上现在很多第三方都有这种控件,如ext.net,fineui等等。这里只是为了学习了解自定义控件的开发。

 

 

 

步入正题

 

1.在vs2010中创建一个类库项目,我选择的框架是3.5。名称“mytextboxcontrol”

 

2.然后新建一个类文件,名称“mytextboxcontrol.cs”

 

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.web;

using system.componentmodel;

using system.web.ui;

using system.web.ui.webcontrols;

using system.security.permissions;

namespace mytextboxcontrol

{

    [

    aspnethostingpermission(securityaction.demand,

        level = aspnethostingpermissionlevel.minimal),

    aspnethostingpermission(securityaction.inheritancedemand,

        level = aspnethostingpermissionlevel.minimal),

    defaultproperty(“text”),

    toolboxdata(“<{0}:mytextboxcontrol runat=\”server\”> </{0}:mytextboxcontrol>”)

    ]

    public class mytextboxcontrol : textbox//继承源生textbox

    {

        /// <summary>

        /// 为textbox扩展的label标签

        /// </summary>

        [

        bindable(true),

        category(“appearance”),

        defaultvalue(“label1:”),

        description(“the control content text.”),

        localizable(true)

        ]

         

        public virtual string label

        {

            get

            {

                string s = (string)viewstate[“label”];

                return (s == null) ? “label1:” : s;//如果控件label为空,默认值为”label1″

            }

            set

            {

                viewstate[“label”] = value;

            }

        }

 

        /// <summary>

        /// 重绘控件

        /// </summary>

        /// <param name=”writer”></param>

        protected override void render(system.web.ui.htmltextwriter writer)

        {

            system.web.ui.webcontrols.label lable = new label();

            lable.id = “label1”;

            lable.text = this.label;//设置标签文本

            lable.font.bold = true;//设置文本显示为粗体

            lable.rendercontrol(writer);//将label输出到控件中

            this.width = unit.pixel(255);//设置默认宽度

            this.text = guid.newguid().tostring(“n”).toupper();//默认文本,设置默认text值

            this.readonly = true;//设置text默认只读

            base.render(writer);//输出控件

        }

 

    }

}

编译项目,会在debug目录下生成mytextboxcontrol.dll文件