ASP.net在页面加载后更改标签文本

本文关键字:标签 文本 加载 net ASP | 更新日期: 2023-09-27 18:29:54

考虑到页面生命周期,我知道这可能是不可能的,但在执行Page_Load方法后,我有没有办法将标签的文本更改为委托的结果。

这是我的代码

public partial class WebForm1 : System.Web.UI.Page
    {
        //private static int Clicks;
        static RaceResult Result;
        protected void Page_Load(object sender, EventArgs e)
        {
            //Label1.Text = Convert.ToString(Session["Clicks"]);
            // First page load?
            if (!IsPostBack)
            {
                Result = new RaceResult(0, "");
                Result.NbrClicksReached += Result_NbrClicksReached;
            }
        }
        private void Result_NbrClicksReached(string message)
        {
            lblRaceResults.Text = (message); //This is the label I would like to change
        }
        protected void btnCounter_Click(object sender, EventArgs e)
        {
            Result.Add(1);
        }
        public delegate void StringDelegate(string message);
        public class RaceResult
        {
            public int Clicks { get; set; }
            public string Name { get; set; }
            public RaceResult(int clicks, string name)
            {
                Name = name;
                Clicks = 0;
            }
            //Delegate
            public event StringDelegate NbrClicksReached;
            public void Add(int amount)
            {
                Clicks += amount;
                if (Clicks == 1)
                {
                    Name = "3rd";
                    if (NbrClicksReached != null)
                        NbrClicksReached(Name);
                }
                if (Clicks == 2)
                {
                    Name = "2nd";
                    NbrClicksReached(Name);
                }
                if (Clicks >= 3)
                {
                    Name = "1st";
                    NbrClicksReached(Name);
                }
            }
        }
    }

这是我的aspx页面

<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnFeed" OnClick="btnCounter_Click" runat="server" Text="Button" />
            <br />
            <asp:Label ID="lblRaceResults" runat="server" Text="Label"></asp:Label>
        </div>
    </form>
</body>

如果无法更改我的标签文本,任何人都可以对我可能添加到Page_Load中的内容提出建议,以使结果显示在标签中

ASP.net在页面加载后更改标签文本

您是否尝试过使用page_loadcomplete然后调用委托?

protected void Page_LoadComplete(object sender, EventArgs e)
    {
      Result_NbrClicksReached(string message);
    }