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.