Click here to Skip to main content
12,299,109 members (50,170 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

8.9K views
4 bookmarked
Posted

Dynamically Register StyleSheet File in ASP.NET

, 20 Feb 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
How to register a stylesheet file at run time

Sometimes it is useful to register an external stylesheet file at runtime dynamically. For example, when we develop portals, this solution can helpful. Because a portal is a comprehensive web based application and a portal user must be able to implement its requirements.

I have a class in my portal that contains useful functions. The name of the class is Functions. In this class, I have many functions that help impement my requirements in a portal. The register stylesheet function is as follows:

public static bool registerStyleSheetFileDynamic(string styleSheetFilePath, System.Web.UI.Page page)
{
 styleSheetFilePath = page.ResolveClientUrl(styleSheetFilePath);
 if (page != null)
 {
  System.Web.UI.HtmlControls.HtmlHead head = (System.Web.UI.HtmlControls.HtmlHead)page.Header;
  bool isExistStyleSheet = false;
  //head.StyleSheet.RegisterStyle(
  foreach (System.Web.UI.Control item in head.Controls)
  {
    if (item is System.Web.UI.HtmlControls.HtmlLink && 
          ((System.Web.UI.HtmlControls.HtmlLink)item).Attributes["href"] == styleSheetFilePath)
     {
      isExistStyleSheet = true;
     }
  }
  if (!isExistStyleSheet)
  {
   System.Web.UI.HtmlControls.HtmlLink link = new System.Web.UI.HtmlControls.HtmlLink();
   link.Attributes.Add("href", page.ResolveClientUrl(styleSheetFilePath));
   link.Attributes.Add("type", "text/css");
   link.Attributes.Add("rel", "stylesheet");
   head.Controls.Add(link);
  }
  return true;
 }
 return false;
}

In this case I can send my arbitrary page and path of stylesheet file to this method in any point in my portal page and so on. I hope the other parts are clear. Thanks!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Saeid.Babaei86
Software Developer FRI
Iran (Islamic Republic of) Iran (Islamic Republic of)
No Biography provided

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160525.2 | Last Updated 20 Feb 2012
Article Copyright 2012 by Saeid.Babaei86
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid