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 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 Dynamicallytitle>
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:
Add CSS Dynamically
No comments:
Post a Comment