How can we alter CSS at runtime using ASP.NET using C#

Category > ASP.NET || Published on : Friday, November 28, 2014 || Views: 10251 || Alter CSS Runrime Alter CSS ASP.NET


In this Tutorial,I will show you to alter the CSS at runtime, below is the source codes throgh which we can attain our objective.  I have placed the label inside div and added runat attribute. In page load, I have assigned the css name to div.

So lets starts the coding.


Step 1: Create a New Website in Visual Studio 2010.
Step 2: Add a new WebForm(Default.aspx) with the following codes.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
"http://www.w3.org/1999/xhtml">
"Head1" runat="server">
    Alter CSS at runtime
    "CSS.css" rel="stylesheet" type="text/css" id="stylesheet" />


    "form1" runat="server">
    
"divName" runat="server"> "Label1" runat="server" Text="SourecCodeHub.com">


Step 3: Create a CSS StyleSheet with name "Stylesheet1.css" with the following codes.

.lblStyle
{
    text-decoration:none;
    font-weight: bold;
    font-size:20px;
    color:#007ddd;
}

Step 4: Add the following codes in Code Behind of the ASPX page already created in step 2.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            divName.Attributes["class"] = "lblStyle";
        }
    }
}

So, In this tutorial we have learned how to alter CSS at runtime. Hope you have enjoyed this tutorial.

 

Download Source Codes