views:

45

answers:

1

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?

+5  A: 

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.

this. __curious_geek
Good solution here
Graphain
Perhaps explain why Page_Load in his derived page classes will also still run.
womp
explained how it works.
this. __curious_geek
@curious_geek: your solution worked as expected. many thanks.
afsharm