Monday, 29 February 2016

how to change CSS dynamically from code behind in asp.net using C#



change CSS dynamically from code behind
Description:-

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:-

<%@ 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:-

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:-
   
body
{
    font-family:Times New Roman;
    font-size:10pt;
}
.label
{
    font-weight:bold;
    color:Purple;
}

 Professional.css:-


body
{
    font-family:Arial;
    font-size:bold;
}
.label
{
    font-weight:bold;
    color:yellow;
}



0 comments:

Post a Comment