User controls can be used to implement reusable code in the page. It is a function that can be written in multiple places at one time and is easy to use. It is the simplest form of ASP.NET control encapsulation.
User controls: User controls contain a combination of html, code, and other Web or user controls, and are saved in their own file format on the Web server, with the extension *.ascx. There is no @Page directive in the user control, but the @Control directive is included, the user control cannot be run as a standalone file, an ASP.net page must be created and added later, the same XHTML elements and web server controls can be used on the user control, e.g. , Button can be placed in a user control and create event handlers for the button.
Note: UserControls can use other UserControls, but cannot contain themselves
Create the user control:
User controls start with @Control
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>
To use a user control in a webform, simply drag and drop the user control into the webform. At this point, the webform has the following code:
<%@ Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %>
If you need multiple pages, you can register the user control once in the configuration file Web.config.
Using user controls:
Drag the user control file .ascx onto the web page you want to use and set the properties.
UserControl.ascx page:
<%@ 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# code:
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:
<%@ 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>
show:
The basic way a web page calls a user control:
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" Text="你好吗" />User controls are generally used for pages that are all used controls and that are repeated a lot.