In this example we explain that how to change CSS dynamically from code behind in asp.net using C#. or how to change CSS file programmatically in C# code(back end code) in asp.net. Some time we have requirement like if user click on or check Lightweight button then Lightweight CSS is apply to the application for these user only same like if user checked or click on Professional button then Professional look is applied to the application for these user only these totally is dynamic and depend on user requirement.
So how to change or switch CSS file dynamically from code behind in asp.net using C#.
ChangeCSSFileDynamically.aspx:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ChangeCSSFileDynamically.aspx.cs" Inherits="WebApplication1.ChangeCSSFileDynamically" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Dynamically change (switch) CSS file programmatically from code behind in ASP.Net</title> <link id="lnkCSS" runat="server" href="~/CSS/Lightweight.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <asp:Label ID="Label1" runat="server" Text="This is a Label" CssClass="label"></asp:Label> <hr /> <asp:RadioButton ID="chkLightWeight" runat="server" GroupName="CSSTheme" AutoPostBack="true" Text="LightWeight" OnCheckedChanged="chkLightWeight_CheckedChanged1" /> <asp:RadioButton ID="chkProfessional" runat="server" GroupName="CSSTheme" AutoPostBack="true" Text="Professional" OnCheckedChanged="chkProfessional_CheckedChanged1" /> </form> </body> </html> |
ChangeCSSFileDynamically.aspx.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class ChangeCSSFileDynamically : System.Web.UI.Page { protected void chkLightWeight_CheckedChanged1(object sender, EventArgs e) { lnkCSS.Attributes["href"] = "~/CSS/Lightweight.css"; } protected void chkProfessional_CheckedChanged1(object sender, EventArgs e) { lnkCSS.Attributes["href"] = "~/CSS/Professional.css"; } } } |
Lightweight.css:
1 2 3 4 5 6 7 8 9 10 |
body { font-family:Times New Roman; font-size:10pt; } .label { font-weight:bold; color:Purple; } |
Professional.css:
1 2 3 4 5 6 7 8 9 10 |
body { font-family:Arial; font-size:bold; } .label { font-weight:bold; color:yellow; } |
Latest posts by Bojan Sorenson (see all)
- Advanced Ways to Improve Your Site’s SEO - September 29, 2017
- How to Optimize DotNetNuke speed by improving page load, caching and use of CDN - September 28, 2017
- How to solve Joomla is not able to install the extensions - September 27, 2017