Monday, July 7, 2008

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

To dynamically set css file, add runat = server and modify this from the page load:

<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


Another way to achive the same is by adding a literal control to the page. The literal contains the link to the css file:

void Page_Load(object sender, EventArgs e)
{
Literal l = new Literal();
l.Text = "<link rel=\"stylesheet\" href=\"mystyle.css\" type=\"text/css\" />";
l.ID = "mystyle";
if(Page.Header.FindControl(l.ID) == null)
Page.Header.Controls.Add(l);
}

No comments: