Load A CSS File For A Specific SharePoint Webpart On The Fly With CssRegistration
Posted on Sunday, 31 May 2009 15:54After 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.
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.
try{ContentPlaceHolder header = (ContentPlaceHolder)this.Page.Master.FindControl("PlaceHolderAdditionalPageHead");if (header != null){string relativePath = this.ClassResourcePath.Remove("://");relativePath = relativePath.Substring(relativePath.IndexOf("/"), (relativePath.Length - relativePath.IndexOf("/")));Literal cssControls = new Literal();cssControls.Text = "";header.Controls.Add(cssControls);}}catch (Exception ex){string relativePath = this.ClassResourcePath.Remove("://");relativePath = relativePath.Substring(relativePath.IndexOf("/"), (relativePath.Length - relativePath.IndexOf("/")));CssRegistration.Register(relativePath + "/mycss.css");}
How do we cope with the "After"?
Please email me, thanks!