用户控件

1. 用户控件可以使开发人员能够根据应用程序的需求,方便的定义和编写控件。

2. 后缀名:.ascx 当用户访问页面时,是不能够被用户直接访问的。

3.用户控件中是没有<html><body>等元素的,主要是因为用户控件页面作为控件被引用到其他页面,而引用的页面已经有了这些元素标签

4.用户控件页面允许用户拖拽服务器控件,并编写相应的样式来实现用户控件,同时还支持事件、方法、委托等。

5. 在 .NET 里,可以通过两种方式把自己的控件插入到 Web 窗体框架中:

  • 用户控件:它是一小段页面,可以包括静态 HTML 代码和 Web 服务器控件。用户控件的好处是一旦创建了它,就可以在同一个 Web 应用程序的多个页面重用它。用户控件可以加入自己的属性,事件和方法。
  • 自定义服务器控件:它是被编译的类,它通过编程生成自己的 HTML 。服务器控件总是预编译到 DLL 程序集。根据你编写服务器控件的方式,可以从零开始呈现它的内容,继承一个现有的服务器控件的外观和行为并扩展它的功能,或者通过实例化和配置一组组合控件来创建界面

创建一个简单的用户控件

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControl_Test.ascx.cs" Inherits="UserControl.DemoTest.UserControl_Test" %>
ID:<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
Name:<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
View Code

用户控件事件:

  protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Write(txtID.Text + "" + txtName.Text);
        }
View Code

使用用户控件:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="UserControl.DemoTest.WebForm1" %>

//引入用户控件 <%@ Register Src="~/DemoTest/UserControl_Test.ascx" TagPrefix="uc1" TagName="UserControl_Test" %>

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div>
//只需要设置ID runat属性,就可以使用用户控件了 <uc1:UserControl_Test runat="server" ID="UserControl_Test" /> </div> </form> </body> </html>

More Information:

http://www.cnblogs.com/SkySoot/archive/2012/09/04/2670678.html

http://www.cnblogs.com/clarkzheng/archive/2007/03/30/Development_And_Use_WebUserControl.html

原文地址:https://www.cnblogs.com/songxia/p/4350830.html