Wiring up the Page_PreInit event manually, with AutoEventWireup set to false
The base implementation of the OnPreInit() method is responsible for raising the PreInit
event. Since your override calls that implementation before registering your PreInit
handler, it will indeed not be called.
Try calling the base class' method after registering the handler:
protected override void OnPreInit(EventArgs e)
{
PreInit += new EventHandler(Page_PreInit);
Load += new EventHandler(Page_Load);
// And only then:
base.OnPreInit(e);
}
CptSupermrkt
Updated on February 07, 2020Comments
-
CptSupermrkt about 4 years
If the
AutoEventWireup
attribute is set tofalse
, the events need to be wired up manually. However, I cannot seem to get thePage_PreInit
to fire. I would guess that I might be making the wireup happen too late (once we're already pastPage_PreInit
), but I'm not sure where else to put the wireups.For example...
protected override void OnInit(EventArgs e) { base.OnInit(e) PreInit += new EventHandler(Page_PreInit); Load += new EventHandler(Page_Load); } protected void Page_PreInit(object sender, EventArgs e) { Response.Write("Page_PreInit event fired!<br>"); //this is never reached } protected void Page_Load(object sender, EventArgs e) { Response.Write("Page_Load event fired!<br>"); }
The above code results in "Page_Load event fired!" being displayed, but nothing from
Page_PreInit
. I triedbase.OnInit(e)
both before AND after the wireups, and that had no effect.The graph shown here says that the
OnInit
method actually comes after thePreInit
event. With that in mind, I tried overridingOnPreInit
and doing the same thing --- no effect.The MSDN article here explicitly says that in the event of
AutoEventWireup
set tofalse
, the events can be wired up in an overridenOnInit
. The example they use isPage_Load
, and of course that works just like it does for me, but they don't address that this doesn't seem to work for thePage_PreInit
event.My question is: how can I get the
Page_PreInit
event wired up in the case ofAutoEventWireup
set tofalse
?I understand there are alternatives as listed on the MSDN page, such as using the page's constructor. I'd like to know specifically how to do like they suggest with
OnInit
.