自定义控件

来源:互联网 发布:centos nginx安装目录 编辑:程序博客网 时间:2024/04/30 08:17

在项目中添加一个用户控件项目,将需要重复性设计的东西放到这个控件中即可,保存该控件后可以直接将这个控件拖到其他页面上来使用

如果对控件中进行改变那么使用该控件的地方也会改变

 

向页面中添加控件的时候会有一句代码

<%@ Register src=”控件位置  tagname=”控件名  tagprefix=”控件组”>

在页面声明指令

 

在使用的地方会有一个控件的声明

 

用户控件是运行时动态添加

 

动态加载控件的实现:

1,在需要动态加载控件的页面上写上代码

UserControl myControl = LoadControl("WebUserControl.ascx") as UserControl;

        Page.Controls.Add(myControl);

 

2,在需要动态加载控件的页面上加入命令

<%@ Reference Control=控件路径>

 

 

4)自定义控件的属性

1,设计组件

2,在用户控件中让其他人来设置属性

在后台代码中写代码实现,代码在类中

//设置文本框颜色

    public System.Drawing.Color textBackColor = System.Drawing.Color.Yellow;

 

    //将控件属性封装

    public string UserName

    {

        get

        {

            return UserName.Text;

        }

        set

        {

            UserName.Text = value;

        }

    }

 

    public string UserPwd

    {

        get

        {

            return UserPwd.Text;

        }

        set

        {

            UserPwd.Text = value;

        }

    }

 

    public int NameLength

    {

        get

        {

            return UserName.MaxLength;

        }

        set

        {

            UserName.MaxLength = value;

        }

}

 

protected void Page_Load(object sender, EventArgs e)

    {

        nameLength.Text = "长度最大为:" + NameLength.ToString();

   }

 

 

清空服务器端的多个文本框

  for (int i = 0; i < this.Controls.Count; i++)

        {

            foreach (Control c in this.Controls[i].Controls)

            {

                if (c.GetType() == typeof(TextBox))

                {

                    (c as TextBox).Text = "";

                }

            }

        }

 

 

Control ct=Page.FindControl("form1");

        ControlCollection cc=ct.Controls;

        foreach(Control c in cc)

        {

            if(c.GetType()==typeof(TextBox))

            {

                (c as TextBox).Text = "";

            }

        }

 

 

可以动态地向页面添加控件

原创粉丝点击