65.9K
CodeProject is changing. Read more.
Home

Dynamically set a link to a CSS file in ASP.NET

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.55/5 (23 votes)

Dec 3, 2004

viewsIcon

133487

VB.NET line of code to dynamically set a link to a CSS file.

Introduction

I had a tough time finding this online so I thought I would post it on CodeProject.com.

I wanted to be able to dynamically set a link to a CSS file. For example, for users to be able to personalize their site, change the look and feel.

Just add a runat attribute to your traditional link tag. ID attribute has to be present, and tag has to be properly closed (not like HTML).

<head>
<link id="MyStyleSheet" rel="stylesheet" type="text/css" runat="server" />
</head>

Then in your Page_Load, simply add a "href" attribute as below:

Sub Page_Load(Sender As Object, E As EventArgs)
 If Not (IsPostBack)
  MyStyleSheet.Attributes.Add("href","/css/flostyle.css")
 End If
End Sub

Nothing fancy, very simple, but very useful. It also works for meta tags.