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.

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

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:// /blog /CommonStylesheet.css")
 End If
End Sub

C# Code:

protected void Page_Load(object sender, EventArgs e)
 commonStyleSheet.Attributes.Add("href", "");

Leave a comment

Your email address will not be published.

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