Having two Page_Load without overriding
I have a class named PageBase
inheriting from ASP.NET Page
. I want to do something in PageBase
's开发者_运维技巧 Page_Load
. All pages in my application have their logic done on their Page_Load
.
I'm thinking of a way that Page_Load
of both of PageBase
and other pages run without having to override Page_Load
in pages. Is it possbile?
Yes, it's possible. Just attach the Page_Load handler within constructor. This is how you do it.
/// <summary>
/// Your PageBase class.
/// </summary>
public class PageBase : System.Web.UI.Page
{
/// <summary>
/// Initializes a new instance of the Page class.
/// </summary>
public Page()
{
this.Load += new EventHandler(this.Page_Load);
}
/// <summary>
/// Your Page Load
/// </summary>
/// <param name="sender">sender as object</param>
/// <param name="e">Event arguments</param>
private void Page_Load(object sender, EventArgs e)
{
try
{
}
catch
{
//handle the situation gracefully.
}
}
}
EDIT
Here's how it works.
Load
is a public event declared in System.Web.UI.Page
which is inherited in the PageBase class as it is. Since this is an event you can attach as many as handler on the event, each of them will be called/executed whenever the Load
event is raised. In the PageBase
class we are attaching an event-handler routine to the Load event. This is better way to do it instead of inheriting the OnLoad protected routine where you need to explicitly call the base version. When the actual Page object is created/instantiated the base class object is created first then the sub-class is instantiated, so when the PageBase object is constructed the event-handler is attached onto the Load event which will be called whenever the Page object fires the Load event.
精彩评论