Themes and Master Pages in ASP.NET 2.0 - A Perfect Combination
page 4 of 6
by Steven Swafford
Feedback
Average Rating: 
Views (Total / Last 10 Days): 32424/ 38

Setting Page Themes at Runtime

There may be occasions when you want to programmatically set the theme for an ASP.NET web form.  For example, your application may utilize a theme for your general user base while application administrators use a completely different theme.  Here is a code snippet that demonstrates how to set the Theme attribute of the web form at runtime.

Listing 6

void Page_PreInit(object sender, System.EventArgs e)
{
    string _role = (string)Session["Role"];
 
    if (_role == "User")
        Page.Theme = "Red";
    else
        Page.Theme = "Blue";
}

Note: The Theme attribute can on be set in the Page_PreInit event.

Let us take setting a theme at runtime a step further.  You may feel it is not efficient to set the theme in each code behind in the web form and in large scale applications you may be better served using a base page to accomplish this.  All you need to do is remove the Page_PreInit event that you previously put in place and move it to the base page.  In order to create the base page, right click on your web site, select Add ASP.NET Folder and select App_Code.  Next add a new class to this folder and name it BasePage.cs.

Figure 5

Once your class is in place, simply add the previous Page_PreInit event to this class.

Listing 7

public class BasePage : System.Web.UI.Page 
{
      public BasePage()
      {
            //
            // TODO: Add constructor logic here
            //
      }
 
    void Page_PreInit(object sender, System.EventArgs e)
    {
        string _role = (string)Session["Role"];
 
        if (_role == "User")
           Page.Theme = "Red";
        else
            Page.Theme = "Blue";
    }   
}

The final step to perform is to extend your web form to utilize this base page.  To do this, remove the inheritance System.Web.UI.Page and replace it with BasePage.

Listing 8

public partial class _Default : BasePage

While either method will work, you will have to determine which is more suitable for your application.


View Entire Article

User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-29 1:10:07 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search