.net用户自定义控件创建

说明:web自定义控件与Winows自定义控件创建差不多,主要区别在于是否要显示出来,从而各自的基类不同

web自定义控件继承于System.Web.UI.Webcontrols.WebControl

下面是创建一般过程:

1:新建web控件库项目,实现INamingContainer接口。

2:为控件添加属性,如<input type="button"/>中的type。

3:重载CreateChildControls()方法,创建复合控件,并为子控件添加必须的方法。

简单的例子如下:

using System;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using System.Drawing;

namespace MyLabel
{

    public class MyLabel : WebControl, INamingContainer
    {
        public MyLabel()
        {
        }
        private string message;
        public string Message
        {
            get { return message; }
            set { message = value; }
        }

        private Label tempLabel;
        protected override void CreateChildControls()
        {
            this.Controls.Add(new LiteralControl("<h1>a simple test</h1><br/>"));
            tempLabel = new Label();
            tempLabel.Text = Message;
            tempLabel.ForeColor = Color.Red;
            this.Controls.Add(tempLabel);

            this.Controls.Add(new LiteralControl("<br/>"));

            Button tempButton = new Button();
            tempButton.Text = "CHANGE COLOR";
            tempButton.Click += new EventHandler(this.Button_Click);
            this.Controls.Add(tempButton);
        }
        protected void Button_Click(object sender, EventArgs e)
        {
          
                tempLabel.ForeColor = Color.Blue;
    
        }

    }
}

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值