Changing Style Sheet Dynamically

Cascading Style Sheets or CSS allow you to easily control the layout and look of your page. CSS tags or properties are easy to use and affect the look and feel or style of your pages. In this article I am posting code about applying style sheets dynamically in an ASP.Net web application.

--- .Css  Pages---


Body {font-family:Arial, Verdana, sans-serif; font-size: 5px; color: #000000;}


/* your styles come here*/




Body {font-family:Arial, Verdana, sans-serif; font-size: 5px; color: #000000;}


/* your styles come here*/


--- .aspx of master page---

Assigned runat ="server" property to access from server side.

<link  href="~/Styles/Site.css" rel="stylesheet" type="text/css"  runat="server" id="lnkStyleSheet"/>

In dropdown add styles sheet as a list item.

<asp:DropDownList ID="ddlStyles" runat="server" AutoPostBack="True" onselectedindexchanged="ddlStyles_SelectedIndexChanged">
<asp:ListItem Text="Original" Value="Styles/Site.css"></asp:ListItem>
<asp:ListItem Text="Day And Night" Value="Styles/DayAndNight.css"></asp:ListItem>

--- .cs of master page ---

protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)
               if (Session["Theme"] != null)
                    lnkStyleSheet.Href = Session["Theme"].ToString().Trim();

                    lnkStyleSheet.Href = ddlStyles.SelectedValue.Trim();

                if (Session["SelectedIndex"] != null)
                    ddlStyles.SelectedIndex = Convert.ToInt32(Session["SelectedIndex"].ToString());


        protected void ddlStyles_SelectedIndexChanged(object sender, EventArgs e)
            lnkStyleSheet.Href = ddlStyles.SelectedValue.Trim(); // assigning style to link href in aspx page
            Session["Theme"] = ddlStyles.SelectedValue.Trim(); // storing selected value in session to maintain across the tabs
            Session["SelectedIndex"] = ddlStyles.SelectedIndex; // storing dropdown selected value in session  to maintain across the tabs


Original Style


Day and night Style


Please give me your comments and advice on this article.
Srinivas Kotra.



Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now