jQuery and ASP.NET

July 23, 2009

How to add CSS Programmatically to an ASP.NET Page




I recently wrote an article on How to add a CSS Link programmatically using JavaScript. A user asked me how to do it in an ASP.NET page. It’s quite simple actually using the HtmlLink class which gives you programmatic access to the HTML <link> element.

Start by adding a reference to the System.Web.UI.HtmlControls namespace. Also make sure that your head tag has the runat=”server” attribute

<head runat="server">
<
title>Add CSS Dynamically</title>
</
head>

Then add the following code in your code behind.

C#

protected void Page_Init(object sender, EventArgs e)
{
HtmlLink link = new HtmlLink();
link.Href = "~CSS/FloatDes.css";
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("type", "text/css");
Page.Header.Controls.Add(link);
}

VB.NET

Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
Dim link As New HtmlLink()
link.Href = "~CSS/FloatDes.css"
link.Attributes.Add("rel", "stylesheet")
link.Attributes.Add("type", "text/css")
Page.Header.Controls.Add(link)
End Sub

Now run your page and check it’s source. You will see the link to the CSS file added in the head element as shown below:

<head><title>

Add CSS Dynamically

</title><link href="~CSS/FloatDes.css" rel="stylesheet" type="text/css" /></head>



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "How to add CSS Programmatically to an ASP.NET Page"
  1. urban said...
    September 19, 2009 8:46 AM

    Perfect! Thanks for this nice tip!

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions