0

I have written the following code in ASP.NET

I have a base page:

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Base Page Called");

    }

I have a derived page which have following code:

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Derived Page Called");

    }

Now while I am calling the Derived page it doesn't call Base Page's Page_Load. It displays

"Derived Page Called".

Now if I change the Derived page Load event handler name to "Page1_Load" and the implementation as following, the Base page is called.

  protected void Page1_Load(object sender, EventArgs e)
    {
        Response.Write("Derived Page Called");


    }

"Base Page Called".

What is the reason for this kind of behaviour?

user1672097
  • 361
  • 1
  • 4
  • 12

1 Answers1

1

Page_Load is automatically wired up if there exists a method with the Page_Load name, so if you define one in the derived class it will hide the one from the base. However, it has to match by name, so by giving the one in the derived class a suffix, it no longer hides the base implementation, so it will pick up the base one and use it.

If you put Page1_Load in the base as well, you will get no output

Base:
protected virtual void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Base Page Called");

    }

Derived:

protected override void Page_Load(object sender, EventArgs e)
{
  base.Page_Load();
  Response.Write("Derived Page Called");
}

Try the above if you want both to be called

TGH
  • 38,769
  • 12
  • 102
  • 135
  • Hide means override? Is there any way so that I can call the Base Page's page load fires automatically, while Derived pages loads in ASP.NET ? – user1672097 Jul 21 '13 at 06:43
  • No hide means hiding it as if it never existed. You can make the one in the base virtual and then override it in the derived class. Try my updated suggestion – TGH Jul 21 '13 at 06:45
  • But for hiding we need new keyword? – user1672097 Jul 21 '13 at 06:54
  • No the new keyword just gets rid of the warning. It is still hidden without it – TGH Jul 21 '13 at 06:55
  • http://stackoverflow.com/questions/1193848/method-hiding-in-c-sharp-with-a-valid-example-why-is-it-implemented-in-the-fram As mentioned here, the new keyword doesn't do much more than removing the warning – TGH Jul 21 '13 at 06:58
  • Thanks a lot for the answer. Now if I want to call base page load in every derived page load, I have to exclusively write base.Page_Load() in every Derived page's page load.Is there way I can do it in one place? – user1672097 Jul 21 '13 at 07:00
  • No, if you want to combine the implementation in both classes, you have to call base.Page_Load from within the overriden method. Otherwise it won't know to combine them. – TGH Jul 21 '13 at 07:06