ASP.NET 用户控件 .ascx

用户控件可用来实现页面中可重用的代码,是可以一次编写多处方便使用的功能,是ASP.NET控件封装最简单的形式。

用户控件:用户控件包含了html、代码和其他Web或者用户控件的组合,并在Web服务器上以自己的文件格式保存,其扩展名是 *.ascx。用户控件中没有@Page指令,而是包含@Control指令,用户控件不能做为独立文件运行,必须创建ASP.net页面,后添加,在用户控件上可以使用相同的XHTML元素和Web服务器控件,例如,Button可以放到用户控件中,并创建按钮的事件处理。

注意:用户控件中可以使用其他的用户控件,但不可包含自己

创建用户控件:


用户控件以@ Control 开头

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>

在webform中使用用户控件只需将用户控件拖webform中即可。此时webform多了如下的代码:

<%@ Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %>

如果需要多个页面使用在配置文件Web.config中注册一次用户控件即可。

使用用户控件:

将用户控件文件.ascx拖到需要使用的web页面上,然后设置属性。

用户控件.ascx页面:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>
<asp:TextBox ID="TextBox1" runat="server" BorderColor="Pink"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="你好吗" BorderColor="Pink" />

C#代码:

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(TextBox1.Text);
        }

        public string Text
        {
            get 
            {
                return TextBox1.Text;
            }
            set
            {
                TextBox1.Text = value;
            }
        }
        public void forecolor(Color color)
        { 
                TextBox1.ForeColor=color;
                Button1.BackColor=color;
        }

webform.aspx页面:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<%@ Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %>

<!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>
        <uc1:WebUserControl1 ID="WebUserControl11" runat="server" Text="你好吗" />
    </div>
    </form>
</body>
</html>

显示:


网页调用用户控件的基本上方式:

<uc1:WebUserControl1 ID="WebUserControl11" runat="server" Text="你好吗" />
用户控件一般用于全部是用控件,且大量重复的页面。






猜你喜欢

转载自blog.csdn.net/qq_41851370/article/details/79854077