Inheritance & Page_Load (again)

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi, this is a follow-up to an earlier question but I really haven't found a
definitive answer in my search

If I have a Base and Derived webform, I've found that the dervived Page_Load
event fires first, then the base Page_Load.

Is the only technique to change this sequence is to override the
Base.Page_Load and explicitely call the base event when you want to as below:

Derived WebForm
--------------------
override private void Page_Load(object sender, System.EventArgs e)
{
base.Page_Load(sender, e); //Run it first
'--Then the rest of dervived code goes here...
}

To me, if you were building a framework and had some generic code in the
base class, that should run first before the derived more specific code.

In the case above, if you wanted the base code to run first, all your
developers would then have to explicitly remember to override and call
base.Page_Load.

If this is the default behavior of asp.net that fine, I just wanted to find
a definate answer.

Thanks, Dave.
 
To me, if you were building a framework and had some generic code in the
base class, that should run first before the derived more specific code.

To me, you should have a choice about it. Sometimes it needs to run in one
order, and sometimes another. Who cares what the default is? What matters is
that you (the developer) knows which order it needs to run in, and codes it
appropriately. And you seem to know that. So, relax and have a cup of
Starbucks!

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
What You Seek Is What You Get.
 
Hi Dave:

This is the default behavior, but let's clarify what's going on.

I assume you are wiring up the event during OnInit in the base class.
Event handlers are invoked in the order in which they were added.
So, if you take a look at the webform designer generated code:

override protected void OnInit(EventArgs e)
{
// CODEGEN: This call is required ...
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}

OnInit, being virtual, will be invoked on the most derived type. In
this case the derived type invokes InitializeComponent and subscribes
to the Load event first. Next, the derived type invokes
base.OnInit(e), where your base class will subscribe to the Load event
in second place.

One solution is to override OnLoad in your base class, perform some
work, and then invoke base.OnLoad. You also might want to review the
design to see why you depend on the order of events firing - it might
be better not to depend on a specific behavior.
 
Back
Top