ASP.NET 自定义控件

创建Web Forms 用户控件

选中项目右键#新建 #Web Forms #Web Forms 用户控件

代码示例

<div id="footer">
    <div style="font-family: @宋体; font-size: 11px;">
        <strong >Martin Emprex Textiles(Zhongshan-China)Limited
        </strong><strong style="color: #5f5f5f;">Copyright &copy; 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);
        }
    }
复制代码

 

posted @   一招致命九虎山  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· PowerShell开发游戏 · 打蜜蜂
点击右上角即可分享
微信分享提示