美文网首页
ASP.NET 自定义控件

ASP.NET 自定义控件

作者: 秒怂的哈士奇爱吃西瓜 | 来源:发表于2024-08-28 11:15 被阅读0次

创建Web Forms 用户控件

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


image.png

代码示例


<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);
        }
    }

相关文章

网友评论

      本文标题:ASP.NET 自定义控件

      本文链接:https://www.haomeiwen.com/subject/shktljtx.html