Site Search:
Sign in | Join | Help
4Penny.net

ASP.NET

Notes, Tricks and Tips on ASP.NET Coding

Dynamic Style Sheet Links in ASP.NET

Earlier I discussed how to dynamically link to background images in ASP.NET. This is a little different, and repuires a little different techniqe. The issue is that when a master page serves a page in a subdirectory, it can't find the style sheet. Not a problem, really, except for the way that ASP.NET 2.0 development works. In development, the site runs as a virtual site, and the path to the css is different in development than when published.

This code will fix that.

Create the css links in the header section of the master page like this:
<link rel="stylesheet" id="Stylesheet1" type="text/css" runat="server" />

The key is the 'id'

Now put this code in the 'on load' event:
Stylesheet1.Attributes("href") = ResolveUrl("~\styles\StyleSheet.css")

That'll fix the problem.

Comments

 

Gray Young said:

Steve-

U R the man !  I needed the dynamic .CSS stuff and found you totally by accident with the solution.  !!!

Happy Holidays to you-all

/r

Gray Y

December 11, 2007 1:24 PM
 

dan said:

Gr8

Thanks

January 29, 2008 11:48 AM
 

Ben said:

Will this work in 1.1?

April 22, 2008 10:28 PM
 

Steve Gray said:

Sure, why not?

April 23, 2008 9:56 AM
 

sarah said:

Says, "Style1 is not declared"

June 15, 2008 1:55 AM
 

Andy said:

It works also in ASP.Net 1.1

You must declare first the "Stylesheet1" in the code behind file.

Add on the *.aspx file the tag <link runat="server" id="Stylesheet1" />

On the code behind add on the top of your class

Protected Stylesheet1 as System.Web.UI.HtmlControls.HtmlGenericControl

And now you can use it on the load event of your page.

Stylesheet1.Attributes.Add("href","../styles/my.css")

Stylesheet1.Attributes.Add("type","text/css")

Stylesheet1.Attributes.Add("rel","stylesheet")

I hope its helpfully.

Greets from Switzerland

Andy

June 20, 2008 4:29 AM
 

Doug said:

Nice tip, thanks

September 20, 2008 9:30 PM

Leave a Comment

(required)  
(optional)
(required)  
Add

About Steve Gray

Steve is a seasoned (translate: old) developer in VB and ASP.NET. He spends most of his time in Dynamics GP, writing custom mods for consulting firms. Crystal reports, eConnect, VS Tools for Dynamics... anything that comes along.