Thursday, October 28, 2010

How to change a theme dynamically

We need to assign a theme in the page preInit event to legimately change the theme dynamically.
protected override void OnInit(EventArgs e)
{
    this.Theme = "Blue";
    base.OnInit(e);
}
However there are couple of challanges if you let users to chose the theme. First one is by the pre-init phase, there are not values loaded for page controls has LoadViewState has not yet been executed.
Solution 1: You can use Request.Form[...] collection.
protected override void OnInit(EventArgs e)
{
    string theme = this.Request.Form[ddlTheme.UniqueID];
    if (!string.IsNullOrEmpty(theme))
        this.Theme = theme;
    else
        this.Theme = "Default";
    base.OnInit(e);
}
Solution 2: You can use a Session variable but we have to re-execute the page to see the session variable.
protected override void OnInit(EventArgs e)
{
    string theme = Session["theme"as string;
    if (!string.IsNullOrEmpty(theme))
        this.Theme = theme;
    else
        this.Theme = "Default";
    base.OnInit(e);
}
protected void ddlTheme_SelectedIndexChanged(object sender, EventArgs e)
{
    Session["Theme"] = this.ddlTheme.SelectedValue;
    Server.Transfer("Page.aspx");
}

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...