Matthew Knott

Previous: Bullitt, the finest car chase ever?
Next: Rounding up in C#

Load A CSS File For A Specific SharePoint Webpart On The Fly With CssRegistration

Posted on Sunday, 31 May 2009 15:54

After wasting a morning trying to get this example of how to get a webpart to register a css file dynamically to work, I realised how it's actually done, and it is far, far simpler.

With the above example, I kept receiving the message "The given path's format is not supported", that was after I turned Custom Errors off, as prior to that all I saw was "Unexpected Error".

You actually only need one line of code in your OnInit or OnPreRender methods.

  1. CssRegistration.Register("/_layouts/css/mycss.css");

There is built-in validation to ensure the file is not registered twice. Enjoy.

Update

I've been using the code below for a long time now, it's the most reliable solution I've found.

  1. try
  2. {
  3. ContentPlaceHolder header = (ContentPlaceHolder)this.Page.Master.FindControl("PlaceHolderAdditionalPageHead");
  4. if (header != null)
  5. {
  6. string relativePath = this.ClassResourcePath.Remove("://");
  7. relativePath = relativePath.Substring(relativePath.IndexOf("/"), (relativePath.Length - relativePath.IndexOf("/")));
  8. Literal cssControls = new Literal();
  9. cssControls.Text = "";
  10. header.Controls.Add(cssControls);
  11. }
  12. }
  13. catch (Exception ex)
  14. {
  15. string relativePath = this.ClassResourcePath.Remove("://");
  16. relativePath = relativePath.Substring(relativePath.IndexOf("/"), (relativePath.Length - relativePath.IndexOf("/")));
  17. CssRegistration.Register(relativePath + "/mycss.css");
  18. }

Comments

  • After, posted by BenHi Matthew,
    How do we cope with the "After"?
    Please email me, thanks!
  • Update, posted by MattHi Ben,

    I've updated this post with the code I use daily. This adds the CSS to the PageAdditionalHead content placeholder and uses CSS Registration only as a backup.

    Hope this helps.

Add a comment