创建Web Forms 用户控件
选中项目右键#新建 #Web Forms #Web Forms 用户控件
![](https://img.haomeiwen.com/i17296796/ea8fe1c62cfae01b.png)
代码示例
<div id="footer">
<div style="font-family: @宋体; font-size: 11px;">
<strong >Martin Emprex Textiles(Zhongshan-China)Limited
</strong><strong style="color: #5f5f5f;">Copyright © Martin ISD Team 2011-<asp:Label ID="labYear" runat="server" Text="-"></asp:Label>
</strong>粤ICP备13024224号
</div>
</div>
后端WebUserControl1.ascx代码
/// <summary>
/// Author: Fly
/// Date: 2022-03-03
/// Dsc: 用户控件
/// </summary>
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
//labYear.Text = DateTime.Now.ToString("yyyy");
}
public void SetVul(string str)
{
labYear.Text = str;
}
}
- 新建WebForm1.aspx调用用户控件
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Web.Control.Demo.WebForm1" %>
<%@ Register Src="~/WebUserControl1.ascx" TagPrefix="uc1" TagName="WebUserControl1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:WebUserControl1 runat="server" id="WebUserControl1" /><br />
<asp:Button ID="Button1" runat="server" Text="获取用户控件数据" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
- 在WebForm1.aspx页面后端获取用户控件的ID并赋值和读取控件信息
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//WebUserControl1.SetVul("Hello World");
//获取用户控件中的服务器控件ID,并赋值
Label label = WebUserControl1.FindControl("labYear") as Label;
label.Text = "Fly";
}
protected void Button1_Click(object sender, EventArgs e)
{
//获取用户控件中的服务器控件ID,并读取控件信息
Label label = WebUserControl1.FindControl("labYear") as Label;
Response.Write(label.Text);
}
}
网友评论