Resources » .NET programming » ASP.NET/Web Applications

Changing themes at Runtime in ASP.NET


Posted Date: 26-Dec-2012  Last Updated:   Category: ASP.NET/Web Applications    
Author: Member Level: Gold    Points: 100


While we have multiple Themes or Designs, why not allow user to change theme of his choice. We are going to learn how to change the Theme of User selection to all pages in solution and also to write something in web.config.



Hello!

As you know about Skins and Themes in ASP.NET in last article. Today we are going to learn how to change themes at runtime.

Requirement


Visual Studio , Visual Web Developer
Basic Knowledge of ASP.NET
Knowledge of CSS
Basic concept of Designs

After Reading this


1. You will learn, how to create theme.
2. How to create Skins
3. How to apply theme to entire solution
4. How to change theme at Runtime.
5. How to save any data to Configuration file (web.config).

Preparing Solution


Create a Empty Web Site in ASP.NET.

1. Add a ASP.NET Theme Folder (App_Themes)
2. Add two theme folders inside App_Themes named Default and myTheme respectively. As used in tutorial, you can change them as per your need.
3. Add Stylesheet and Skin file with same name of theme inside the newly created folders.
4. Write some CSS code and put images inside theme folder.
5. Add a web-form with name Default.aspx.
Now your Solution Explorer might be looking like this.

Solution Explorer

Style Sheet, Skin File and Web Form.



Now see the Code for Default.css

body {
background-image: url(images/bgimg.jpg);
background-repeat: repeat-x;
color: black;
}

.header {
background-image: url(images/header.png);
background-repeat: repeat-x;
text-align: right;
text-transform: uppercase;
vertical-align: bottom;
font-size: 32px;
font-weight: 800;
padding-top: 150px;
padding-bottom: 4px;
padding-right: 5px;
}

.menubg {
background-image:url(images/menu_bg.jpg);
}

.menu {
align-items:stretch;
padding: 14px 14px 14px 14px;
color: White;
font-family: Calibri;
font-size: larger;
font-variant: small-caps;
text-align: center;
font-weight: 800;

}


.footer {
background-image:url(images/menu_bg.jpg);
color: #4cff00;
text-align: center;
font-size: small;
font-family: Segoe UI, Calibri, Verdana;
}

a {
font-family: Tahoma, Comic Sans MS, Calibri;
font-size: inherit;
text-decoration: none;
color: #656545;
}

h1 {
font-family: Calibri, Verdana, Tahoma, Segoe UI;
font-size: x-large;
font-variant: small-caps;
text-align: center;
}


Code for Default.skin

<asp:TextBox runat="server" BackColor="lightblue" ForeColor="Black" Font-Bold="true" BorderWidth="2px" BorderStyle="Solid"></asp:TextBox>

<asp:Button runat="server" BackColor="yellow" ForeColor="Black" Font-Bold="true" BorderWidth="2px" BorderStyle="Solid" />

<asp:GridView runat="server" HeaderStyle-BackColor="red" AlternatingRowStyle-BackColor="lightgreen"></asp:GridView>

I am not posting the code of myTheme.css and myTheme.skin here because the styles and skin is same with some image and color change.

Now come to Default.aspx code.

<table width="950px" align="center" border="2">
<tr>
<td class="header">P.Yar.B Complex
</td>
</tr>
<tr>
<td align="center" class="menubg">
<asp:LinkButton ID="lnkHome" runat="server" Text="Home" CssClass="menu"></asp:LinkButton>
<asp:LinkButton ID="lnkAbout" runat="server" Text="About" CssClass="menu"></asp:LinkButton>
<asp:LinkButton ID="lnkProfile" runat="server" Text="Profile" CssClass="menu"></asp:LinkButton>
<asp:LinkButton ID="lnkContact" runat="server" Text="Contact" CssClass="menu"></asp:LinkButton>

</td>
</tr>
<tr>
<td class="body">
<div align="center">
Choose Theme :
<asp:DropDownList ID="ddlTheme" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlTheme_SelectedIndexChanged">
<asp:ListItem Value="0">Select</asp:ListItem>
<asp:ListItem Value="1">Default</asp:ListItem>
<asp:ListItem Value="2">myTheme</asp:ListItem>
</asp:DropDownList>

<h1>Customer Search</h1>
Name :
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<br />
<h3>Customers</h3>
<asp:GridView ID="GridView1" runat="server" Width="447px" AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
<asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle" SortExpression="ContactTitle" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
<asp:BoundField DataField="Region" HeaderText="Region" SortExpression="Region" />
<asp:BoundField DataField="PostalCode" HeaderText="PostalCode" SortExpression="PostalCode" />
<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
<asp:BoundField DataField="Fax" HeaderText="Fax" SortExpression="Fax" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT * FROM [Customers] WHERE ([ContactName] LIKE '%' + @ContactName + '%')">
<SelectParameters>
<asp:ControlParameter ControlID="txt1" Name="ContactName" PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</div>

</td>
</tr>
<tr>
<td class="footer">All Rights reserved. Copyright 2012 , P.Yar.B Complex
</td>
</tr>
</table>


Above code will produce below Design without any theme.

Design on Form

I have created a basic layout using HTML Table. First row is Header, second is Menu, third is Body and Last one is footer. This is very simple layout.

The Backend code for Button click is same as in previous tutorial, it is just binding Gridview. Now one major task is to write the Code to change the Theme of User Selection. As you notices, I have created a Dropdownlist in above design with two Elements (items). One is Default and another is myTheme.

Logic and Concept


We want to change the theme of user selection for whole website. It means all the pages. This can be achieved by two ways. By putting a variable in Session and getting this every-time on Page_PreInit or changing the value of Web.config.
I am here going to change the theme name in web.config that we put the Last time inside System.web node and Pages element of Root.


<system.web>
<pages theme="myTheme" />
</system.web>


This will product following changes in our output.

Output on Browser

We will access this value and change according to user selection on DropDownList Selected Index Changed event.

Backend code of Default.aspx (C#)


This code is for Button Click event and DropDownList SelectedIntexChanged event. .

Namespaces to Include

using System.Configuration;
using System.Web.Configuration;


Button Click Event

protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataBind();
}

DropDownList SelectedIndexChanged Event

protected void ddlTheme_SelectedIndexChanged(object sender, EventArgs e)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
PagesSection pages = (PagesSection)config.GetSection("system.web/pages");
pages.Theme = ddlTheme.SelectedItem.Text.ToString();
if (!pages.SectionInformation.IsLocked)
{
config.Save();
Response.Redirect("Default.aspx");
}

Now just Browse webpage with browser and change the theme using Theme Selection List.

This is the Output, when I choose Default from theme List.

Output on Browser-Changed

A working source code is attached with the Resource. You can use this at your system by just changing the connectionstring in web.config to point towards northwind database in your system. (This is only required to load GridView data.)
All the Best.

John Bhatt
P.Yar.B Complex


Did you like this resource? Share it with your friends and show your love!

Responses to "Changing themes at Runtime in ASP.NET"
Author: Vinod Kumar Sahu    10 Feb 2013Member Level: Silver   Points : 6
1) Create one session variable which will hold current theme value
2) On selection change event of dropdown combo box , assign value form combo box to session variable.
3) During Page_preInit Event assign this variable value to Page.Theme property.
4) 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);

}



Author: John Bhatt    11 Feb 2013Member Level: Gold   Points : 2
Hello Vinod,

Thanks for you code. As you know, there might be many ways to achieve same target.
Above tutorials is created for basic users and using simplest code. Your code is also perfect.
Why don't you write an article containing some Images and the code for above task.

By the way, thanks for reading my article.



Guest Author: Momina     07 May 2013
It is very helpful .Thanks for creating such a helpful website.(y)


Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index

    Subscribe to Subscribers
    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    Pawan Awasthi
    More...
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India