How To Add CSS reference to header from code behind (C#)

Adding CSS reference in a web form is very easy but sometimes we need to add it dynamically from code. In this post, I will show you how to add CSS reference to the header from the code behind (C#).

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="tylesheetCodebehind.aspx.cs"
   Inherits="tylesheetCodebehind" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Change style" /></div>
   </form>
</body>
</html>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class tylesheetCodebehind : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HtmlLink css = new HtmlLink();
        css.Href = ResolveClientUrl("~/style/StyleSheet.css");
        css.Attributes["rel"] = "stylesheet";
        css.Attributes["type"] = "text/css";
        css.Attributes["media"] = "all";
        Page.Header.Controls.Add(css);

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        HtmlLink css = new HtmlLink();
        css.Href = ResolveClientUrl("~/style/StyleSheet2.css");
        css.Attributes["rel"] = "stylesheet";
        css.Attributes["type"] = "text/css";
        css.Attributes["media"] = "all";
        Page.Header.Controls.Add(css);


    }
}

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post