joe doe
joe doe

Reputation: 1

page_load another handler?

can someone please explain why this code is not working as expected:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class temp : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("foo<br>");
        this.Load += new EventHandler(temp_Load);

    }

    void temp_Load(object sender, EventArgs e)
    {
        Response.Write("bar<br>");
        Response.End();
    }
}

trying to add another handler for page Load event so that output would be:

foo<br>
bar<br>

EDIT:

The actual object disappears and is recreated on postback. – ggonsalv

so how can i than modify the method in memory so it makes new objects with that modified method?

for example i want to modify or add page_init handler on runtime for the next time the page loads?

Upvotes: 0

Views: 241

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You cannot modify the Load handler from withing the handler itself. It's too late as it is already executing. Why not simply calling a function as it doesn't make much sense of having multiple load handlers for the same page:

protected void Page_Load(object sender, EventArgs e)
{
    Response.Write("foo<br>");
    temp_Load(sender, e);
}

Upvotes: 0

ggonsalv
ggonsalv

Reputation: 1262

You need to register it in the Page_Init. By the time Page_load fires, it is toooooo late.

Upvotes: 1

Related Questions