Load CSS Dynamically in ASP.Net (C# & VB.Net)

Mohammed Imtiyaz Dec 10, 2014

Sometimes it is necessary to programmatically add some CSS stylesheets to your ASP.Net page, for example if you want to allow your users to change look and feel of your website by choosing themes, etc.


Add the following namespace in your CodeBehind

using System.Web.UI.HtmlControls;

Now bind the css dynamically from CodeBehind

protected void Page_Init(object sender, EventArgs e) {
    HtmlLink css = new HtmlLink();
    css.Href = "css/style.css";
    css.Attributes["rel"] = "stylesheet";
    css.Attributes["type"] = "text/css";
    css.Attributes["media"] = "all";


Imports System.Web.UI.HtmlControls
Protected Sub page_init(ByVal sender As Object, ByVal e As EventArgs)
   Dim css As New HtmlLink()
   css.Href = "css/style.css"
   css.Attributes("rel") = "stylesheet"
   css.Attributes("type") = "text/css"
   css.Attributes("media") = "all"
End Sub