Dynamically adding a CSS link to the page in c#

The following code adds a CSS link to the header node of a Html page.

// register css
HtmlHead head = (HtmlHead)Page.Header;
HtmlLink link = new HtmlLink();
link.Attributes.Add("href", Page.ResolveClientUrl("~/App_Themes/Default/StyleSheet.css"));
Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.


Randi said:

Thanks!! this fixed my issue!!

22/Sep/2008 22:23 PM

Rahul Tyagi said:

Thanks it fixed my issue


30/Dec/2008 07:08 AM

Manpreet said:

Can we use following one line code to link the css page in head tag?

<link href="Style.css" rel="stylesheet" type="text/css" />

this too works

08/May/2009 06:20 AM

phayman said:

You can ad it in the Head tag, but in this example, we want to specify it dynamically.. different styles for different pages, browsers etc.

21/Aug/2009 11:03 AM

IIPPP said:

LOL Manpreet you suck

24/Sep/2009 06:50 AM

srinivas N said:

This code doesn't work when we have <% * %> tags under <head> tag.

In this case we will get a run time error mesage

"The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>."

30/Dec/2009 13:37 PM

jj said:

hi i am using this concept in my application. Style sheet is dynamically changed. that's working fine . Is there any idea for my below question?

1. button click event i called one page . in that page i have used this dynamic style change functionality. First time the style is not changed after refresh only the style is changed

05/Feb/2010 09:23 AM

Fernando said:

Thank you, solved my problem!

02/Mar/2010 21:31 PM

shady said:

thanks alot man, this was really helpful....... best source i've found on this topic.

i really appreciate it

25/Dec/2010 09:28 AM

figgi said:

hey guyz! iv really been having a problem with my code i get the error

Object reference not set to an instance of an object. at the line [head.Controls.Add(link); ]

who knows what am not doing?

19/Jan/2011 15:42 PM

Add Comment


Your comment has been received and will be shown once it passes moderation.