Add CSS StyleSheet Link in ASP.NET page header at runtime

Friday, 24 April 2009 10:55 by myro

Is not really intuitive how can you add a reference to a css stylesheet at runtime in ASP.NET in the HTML head section: you need to call the page's ClientScript manager and register a Javascript script block defining your script code as a link tag. Remember that RegisterCssReference method will only work if you call it before the page's OnRender event method, so use it in OnLoad and OnPreRender page's events.

protected void RegisterCssReference(string CssLinkurl)
{
       if (!String.IsNullOrEmpty(CssLinkurl))
       {
           String sb = String.Empty;
           sb = String.Concat("<link rel=\"stylesheet\" href=\"", CssLinkurl,
                 "\" type=\"text/css\" media=\"screen\" />");
           Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "YOUR_KEY", sb , false);
       }
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   ,
Categories:   .NET | Web
Actions:   Bookmark and Share | Permalink | Comments (0) | Comment RSSRSS comment feed
If you consider this post usefull for your purposes, please consider visiting my sponsors to help me out with the myrocode.com maintenance. Thank you.