Dynamically Add CSS in ASP.NET Content Page

You are currently viewing Dynamically Add CSS in ASP.NET Content Page

One of the best features Microsoft added in ASP.NET 2.0 is the introduction of Master Pages. ASP.NET automatically add basic HTML mark up in the master page such as html, head, title and body tag and allows developers to add content pages of the website to fill content place holders in the Master Page. By using these basic HTML elements developers can add external CSS and Java Script files just once in Master Page and all the content pages get those files automatically.

Sometimes, developers need to inject CSS or Java Script dynamically for some specific ASP.NET pages. As head tag of html is not allowed in ASP.NET content pages so developers need to add these two files dynamically through C# or VB.NET code.

In the following tutorial I will show you how you can add both internal and external CSS dynamically in ASP.NET 2.0 content page.

Add CSS style properties

VB.NET

Dim cssStyle As New Style()
cssStyle.ForeColor = System.Drawing.Color.Navy
cssStyle.BackColor = System.Drawing.Color.LightGray
Me.Header.StyleSheet.CreateStyleRule(cssStyle, Nothing, "body")

C#

Style cssStyle = new Style(); 
cssStyle.ForeColor = System.Drawing.Color.Navy; 
cssStyle.BackColor = System.Drawing.Color.LightGray; 
this.Header.StyleSheet.CreateStyleRule(cssStyle, null, "body"); 

Add External CSS file

VB.NET

Dim cssLink As New HtmlLink()
cssLink.Attributes.Add("type", "text/css")
cssLink.Attributes.Add("rel", "stylesheet")
cssLink.Attributes.Add("href", "~/styles/MyStyle.css")
Me.Header.Controls.Add(cssLink)

C#

HtmlLink cssLink = new HtmlLink(); 
cssLink.Attributes.Add("type", "text/css"); 
cssLink.Attributes.Add("rel", "stylesheet"); 
cssLink.Attributes.Add("href", "~/styles/MyStyle.css"); 
this.Header.Controls.Add(cssLink); 
READ ALSO:  Using ASP.NET AJAX HoverMenu Control with GridView

This Post Has One Comment

  1. Attiq

    this is what I was looking for 🙂

Leave a Reply