2012-06-18

Dynamically add a reference to a css file

Have a <link> tag in your aspx page

<link id="CSSFile" type="text/css" rel="Stylesheet" runat="server" />

And add the href attribute for the link tag from code behind, like below

protected void Page_Init(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
         CSSFile.Attributes.Add("href", "Dynamic.css");
    }
}

The reason I do this on Page_Init method is Page_Init would be the better place to place this kind of code since Page_Init() method fires before Page_Load event. Page_Init() is usually what we use to do the initialization steps. Page_Init() method fires only the first time the page is loaded. It will NOT fire everytime when there is a postback.

No comments: