shenn
shenn

Reputation: 887

Compiler error when overriding Page_PreInit

I am trying to override the Page_PreInit function inside my class _Default which inherits from Page. However, when I try to compile I get the following error:

'_Default.Page_PreInit(object, System.EventArgs)': no suitable method found to override

Here is my code:

public partial class _Default : Page
{
    protected override void Page_PreInit(object sender, EventArgs e)
    {
        // Todo:
        // The _Default class overrides the Page_PreInit method and sets the value
        //  of the MasterPageFile property to the current value in the 
        //  selectedLayout session variable.

        MasterPageFile = Master.Session["selectedLayout"];
    }

    ...
}

Upvotes: 0

Views: 4602

Answers (1)

Michael Liu
Michael Liu

Reputation: 55529

The Page class declares a public event named PreInit and a protected virtual method named OnPreInit (which just raises the PreInit event). So you have two options.

Option 1 (recommended): Override OnPreInit:

protected override void OnPreInit(EventArgs e)
{
    // Set the master page here...

    base.OnPreInit(e);
}

Call base.OnPreInit(e) so that the page raises the PreInit event as usual.

Option 2: Create a method named Page_PreInit. ASP.NET will automatically bind this method to the PreInit event as long as you don't set AutoEventWireup to False in the @Page directive or in Web.config.

private void Page_PreInit(object sender, EventArgs e)
{
    // Set the master page here...
}

If you choose this option, don't call base.OnPreInit, or else you will end up with an infinite recursion.

Upvotes: 5

Related Questions