There are a variety of techniques out there for wiring up a CSS class to an ASP.NET Web Form through code. You can register a link to a CSS file via Page.Header.Controls.Add() and ASP.NET 2.0 introduced the robust WebResource framework for registering entire style sheets for a given page, but what about when you want to add a dynamic style to the HTML header?
Typically, the technique would involve something like this:
Page.Header.Controls.Add(
new LiteralControl(
@"<style type='text/css'>
/*type selector*/
BODY
{
background: Aqua;
}
/*class selector*/
.myClass
{
background: WhiteSmoke;
font-size: 20pt;
}
</style>
"
)
);
...but there are drawbacks to the approach including the need for verbose "style" tags with each chunk of CSS styles you want to add and the lack of validation on style names and values.
Luckily, there's a more sophisticated and elegant approach supported by .NET Framework 2.0 or higher using Page.Header.Stylesheet and the System.Web.UI.WebControls.Style class. With the approach, instead of having to define your CSS class using a string, you can used strongly-typed objects instead! Additionally, all of the styles you add will get added to one single style attribute in the Page header.
Style typeStyle = new Style();
typeStyle.BackColor = Color.Aqua;
Page.Header.StyleSheet.CreateStyleRule(typeStyle, null, "BODY");
Style classStyle = new Style();
classStyle.BackColor = Color.WhiteSmoke;
classStyle.Font.Size = FontUnit.Parse("20pt");
Page.Header.StyleSheet.CreateStyleRule(classStyle, null, ".MyClass");
There is, however, a drawback to the approach which is the limited number of properties available in the Style base class. For instance, if you wanted to set a value for the "margin" CSS style, you'd need to either use or create a subclass of Style that overrides the AddAttributesToRender() method.