Introduction
This is a simple code which can be used to change page themes at runtime.
Background
Basic knowledge of stylesheets is required.
Using the code
Live Demo
Before we proceed further I would recommend you to see live demo here to get idea what we are talking about.
Challenges
At first though we may say we can easily achieve this by coding it in Page_Preinit Event as shown below.
protected void Page_PreInit(object sender, EventArgs e)
{
Page.Theme = "Black"
}
But problem with this is we cant assign value from dropdown box because Page_Preinit event is fired much before dropdown has changed value.
Solution
- Create one session variable which will hold current theme value
- On selection change event of dropdown combo box , assign value form combo box to session variable.
- During Page_preInit Event assign this variable value to Page.Theme property.
- Stop page loading and reload same page again using server.transfer method as shown below
protected void Page_PreInit(object sender, EventArgs e)
{
string thm;
thm = (string)Session["themeSelected"];
if (thm != null)
{
Page.Theme = thm;
DropDownList1.Text = thm;
}
else
{
Session["themeSelected"] = DropDownList1.Text;
Page.Theme = "Blue";
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["themeSelected"] = DropDownList1.Text;
Server.Transfer(Request.FilePath);
}
Summary
Problem was solved by using session variable and refreshing page at page load event by server.transfer method
Download
Fully functional source code with example can be downloaded from here
Points of Interest
- Page_preinit is fired much before control initialization
- Session variable used to store and retrieve page theme at page load event
- server.transfer play important role here