Dynamically assign a Style Sheet to an ASP.NET page

Sunday, January 11, 2004
One popular personalization feature is to allow users to select a “skin” for your site (the new MSN home page has some nice looking color schemes to choose from). While ASP.NET server controls allow you to assign a style sheet class easily (the Class property), there is no property or method to set the stylesheet (or stylesheets) assigned to a page.

One easy way to do this is to replace your LINK tag in the ASPX with a Literal server control. The Literal control is a placeholder for rendering text into the HTML. By assigning your LINK tag to the Text property of a Literal, you manage the style sheet of a page from the code behind.

Here is an example ASPX file

<%@ Page language="c#" Codebehind="DynamicStyleSheet.aspx.cs"
 AutoEventWireup="false" Inherits="aspnet.DynamicStyleSheet" %
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
		<asp:Literal id="StyleSheet" runat="Server" />
	<body MS_POSITIONING="GridLayout">
		<form id="Form1" method="post" runat="server">
			<h6>hello world</h6>

The corresponding code behind file

public class DynamicStyleSheet : System.Web.UI.Page
   protected System.Web.UI.WebControls.Literal StyleSheet;

   private void Page_Load(object sender, System.EventArgs e)
         const string styleFormat = 
           "<LINK href='\"{0}\"' type='\"text/css\"' rel='\"stylesheet\"'>";

         string linkText;
         linkText = String.Format(styleFormat, StyleSheetPath);
         StyleSheet.Text = linkText;         

   protected string StyleSheetPath
         // pull the stylesheet name from a database or xml file...
         return ApplicationPath + "MyStyle.css";

   private string ApplicationPath
         string result = Request.ApplicationPath;
            result += "/";
         return result;

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!