In this article I will explain how to dynamically change the CSS class file programmatically from code behind in ASP.Net using C# and VB.Net i.e. set its CSS set link to the CSS class file.
	
		Basically I’ll have created two buttons to switch the CSS class files.
	
	
		 
	
		 
	
		HTML Markup
	
		The HTML Markup contains an HTML <link> element to which I have set runat="server" attribute so that I can easily access it from code behind. Also I have placed two ASP.Net <asp:Button>controls which will dynamically switch the CSS files in their click event handler ChangeCSS.
	
		Also you will notice that I have set the CommandArgument property for the ASP.Net Buttons to the name of the CSS class files.
	
		Finally I have used an ASP.Net <asp:Label>control which will act as an indicator to let us know the change dynamic change of the CSS class files.
	
		
			<html xmlns="http://www.w3.org/1999/xhtml">
		
			<head runat="server">
		
			    <title></title>
		
			    <link id="lnkCSS" runat="server" href = "~/CSS/Default.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:Button ID="Button1" runat="server" Text="CSS 1" OnClick="ChangeCSS" CommandArgument="CSS1.css" />
		
			    <asp:Button ID="Button2" runat="server" Text="CSS 2" OnClick="ChangeCSS" CommandArgument="CSS2.css" />
		
			    </form>
		
			</body>
		
			</html>
	 
	
		 
	
		 
	
		The CSS Files
	
		For this article I have created following three CSS class files, Default.css, CSS1.css and CSS.css.
	
		Default.css
	
		
			body
		
			{
		
			    font-family:Arial;
		
			    font-size:10pt;
		
			}
		
			.label
		
			{
		
			    font-weight:bold;
		
			    color:Black;
		
			}
	 
	
		 
	
		 
	
		CSS1.css
	
		
			body
		
			{
		
			    font-family:Arial;
		
			    font-size:10pt;
		
			}
		
			.label
		
			{
		
			    font-weight:bold;
		
			    color:Red;
		
			}
	 
	
		 
	
		 
	
		CSS2.css
	
		
			body
		
			{
		
			    font-family:Arial;
		
			    font-size:10pt;
		
			}
		
			.label
		
			{
		
			    font-weight:bold;
		
			    color:Blue;
		
			}
	 
	
		 
	
		 
	
		 
	
		Dynamically changing (Switching) CSS class files on Button click
	
		In the below click event handler I am dynamically setting the CSS class file path using the file name from the CommandArgument property of the ASP.Net Button.
	
		C#
	
		
			protected void ChangeCSS(object sender, EventArgs e)
		
			{
		
			    lnkCSS.Attributes["href"] = "~/CSS/" + (sender as Button).CommandArgument;
		
			}
	 
	
		 
	
		VB.Net
	
		
			Protected Sub ChangeCSS(sender As Object, e As EventArgs)
		
			    lnkCSS.Attributes("href") = "~/CSS/" + TryCast(sender, Button).CommandArgument
		
			End Sub
	 
	
		 
	
		 
	
		Demo
	
	
		 
	
		Downloads