How to dynamically change the style sheet based on browser type

R

Rob Roberts

In a VS2005 ASP.NET project, I'm trying to find a way to change which css
file is linked in based on the browser type. I'd like to use one css file
for IE browsers, and a different one for all other browsers. I'm using a
MasterPage. I added a Literal control to the Head section of the
MasterPage, and then in the Page_Load event I set its Text property to set
up the desired link, like this:

StyleSheetLiteral.Text = "<link rel=\"stylesheet\" type=\"text/css\"
href=\"/inc/content_ie.css\">";

This works, but the VS2005 IDE reports it as an error, with message
"Unrecognized tag prefix or device filter 'asp'." Plus I can't help
thinking that there must be a better way.

I also tried setting the Page.StyleSheetTheme property in the Page_Load
event, but this gives a System.InvalidOperation exception when the page
loads. The documentation for Page.StyleSheetTheme says that it must be set
before the page's Init event completes, but I can't figure out how to access
that event in the MasterPage.

Any ideas on the best way to accomplish setting the style sheet dynamically?

Thanks in advance,
--Rob Roberts
 
G

Guest

The <link>tag in ASP.NET 2.0 can runat=server, e.g. you can place on the
master page:
<link runat="server" id="StyleLink1" type="text/css"/>

You can access it directly on the master page like this:
StyleLink1.Href ="MyStyleSheet";

Or you can access it in the content page like this:

//assuming that you have
//<%@ masterType VirtualPath="~/MasterPage.master" %> in your page markup
HtmlLink lnk = (HtmlLink)Master.FindControl("StyleLink1");
if (lnk != null) lnk.Href="MyStyleSheet";
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top