C# – Why can’t Themes and Master pages be applied dynamically after Page.PreInit event

asp.netcmaster-pagesthemeswebforms

1) I assume Themes can be set programatically only inside Page.PreInit event handler due to the following reasons:

  • if we’d set a Theme inside Page.Init event handler, then by that time ViewState would already be tracked and thus any data applied by Theme would be tracked and marked as dirty ( which would consume lot of bandwidth ) ?

  • and if we’d set it after Init event, then Themes could also override deserialized ViewState data applied to individual controls?

Are there any other reasons why Themes can’t be set after Page.PreInit?

2) Also, why can't Master pages be applied after Page.PreInit?

thanx

Best Answer

According to this:

http://odetocode.com/articles/450.aspx

The 'MasterPageFile' property can only be set in or before the 'Page_PreInit' event.

This exception makes sense, because we know the master page has to rearrange the page’s control hierarchy before the Init event fires

The article also includes this example:

using System;
using System.Web.UI;

public class BasePage : Page
{
   public BasePage()
   {
        this.PreInit += new EventHandler(BasePage_PreInit);
   }

    void BasePage_PreInit(object sender, EventArgs e)
    {
        MasterPageFile = "~/Master1.master";
    }
}

Or, an approach I've used before:

protected override void OnPreInit(EventArgs e) 
    { 
        base.OnPreInit(e); 
        if (Request.QueryString["Master"] == "Simple") 
            MasterPageFile = "~/Masterpages/Simple.Master"; 
    } 
Related Topic