Add CSS Programatically in ASP.NET

We Can set (Register) the Javascript file in ASP.NET but there is no such method for the CSS. So i have decided to write the article on how to set the CSS path dynamically in ASP.NET and C#.

To achieve, just add runat attribute in link tag and access it at code behind.

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

after this, in Page Load method just add attribute href as shown below.

VB Code:

Sub Page_Load(Sender As Object, E As EventArgs)
 If Not (IsPostBack)
    commonStyleSheet.Attributes.Add("href","http:// www.JitendraZaa.com /blog /CommonStylesheet.css")
 End If
End Sub

C# Code:

protected void Page_Load(object sender, EventArgs e)
{
 commonStyleSheet.Attributes.Add("href", "https://www.jitendrazaa.com/blog/CommonStylesheet.css");
}

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.