简体   繁体   中英

ASP.net change Label text after Page Load

I know it might not be possible considering the Page Lifecycle but is there any way I could change the text of a label to the result of my delegate after the Page_Load method has been executed.

This is my code

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

This is my aspx page

<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>

If it is not possible to change my labels text could anyone make a suggestion to what I might add to my Page_Load to get the result to display in the label

Have you tried using page_loadcomplete and then calling the delegate?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM