Tuesday, November 23, 2010

ASP.NET Change Page Theme on Run time

A simple question about setting themes in ASP.NET would be of in which event I can set the or change the Theme of my page. Like if i want to give an option for user to select from list of available themes and the site on run time could be changed to a specific theme.

Can in Change theme on button click?
How to change theme on click of button?

The answer was simple after reading the documentation of System.Web.UI.Page.Theme() property:

Property: Public Overridable Property Theme() As String
Member of: System.Web.UI.Page
Summary: Gets or sets the name of the page theme.
Exceptions:
System.InvalidOperationException: An attempt was made to set System.Web.UI.Page.Theme after the System.Web.UI.Page.PreInit event has occurred.
System.ArgumentException: System.Web.UI.Page.Theme is set to an invalid theme name.


The 'Theme' property can only be set in or before the 'Page_PreInit' event.

I have made a work around to change the theme on run time on click of a button:

Partial Class Default
Inherits System.Web.UI.Page

Protected Sub btnChange_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnChange.Click
'Cannot change theme on Click event
End Sub

Protected Sub Page_PreInit(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.PreInit
'If Page is postback
If Me.IsPostBack = True Then
If Not Request(btnChange.UniqueID) Is Nothing Then
Me.Page.Theme = "NewTheme"
End If
End If

End Sub

End Class


We have still changed the theme in 'Page_PreInit' event but on click of a button.

UniqueID of a control gets the unique, hierarchically qualified identifier for the server control. The fully qualified identifier for the server control, this is ID which is received as key when value is post back.

The output of button is like this:
<input type="submit" name="btnChange" value="Change Theme" id="btnChange" />

Here name is what we call btnChange.UniqueID and id is what we call btnChane.ClientID, in HTML input controls "id" is used for client side validation and other java script things, and "name" attribute is used to identify the field when it is post back to server.

No comments:

Post a Comment