Dynamically changing themes in asp.net
Themes are styling objects in asp.net. We can set the themes by using Theme page directive or by adding or modifing <pages theme=”" /> tag Web.config.
But if you want to change it in run-time you need to set the theme in the Page_PreInit event in the ASP.Net Page Life-Cycle.
Simple implementation of changing theme in dynamically in asp.net
In this there is a dropdown list which displays all the theme / skin files in the current application, with autopostback enabled.
Page_Load event
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
foreach (string dir in Directory.GetDirectories(Request.MapPath("./App_Themes")))
{
this.ThemeSelector.Items.Add(new ListItem(Path.GetFileNameWithoutExtension(dir), Path.GetFileNameWithoutExtension(dir)));
}
this.ThemeSelector.Items.Insert(0, new ListItem("-- SELECT --", "-1"));
}
}
Dropdown selected Index change Event
protected void ThemeSelector_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.ThemeSelector.SelectedValue != "-1")
{
Session["theme"] = this.ThemeSelector.SelectedValue;
}
}
Page_PreInit event
protected void Page_PreInit(object sender, EventArgs e)
{
if (Session["theme"] != null)
{
this.Theme = Session["theme"] as string;
}
}
The selected theme is storing into a session variable in selected Index change event and in the Page preinit event it is setting as the current page’s theme. This can be applied to all the pages in a web application, because we are using Session variable.