Adding a CSS Stylesheet to a Web Part

9 November, 2015

Adding a CSS Stylesheet to a Web Part

This is something that you would think would be really easy, after all you should always separate the styles out from your code. However, I had great difficulty finding anything on the web about it. I finally managed to crack it and am posting it here for others to find. 

Basically you can add an HtmlLink control to the Headers collection of the page.

        ///

Adds the stylesheet to the page.

        void AddStyleSheet()
        {
            string url = “~/_layouts/misWebParts/misWebParts.css”;
            foreach (Control control in Page.Header.Controls)
            {
                HtmlLink link = control as HtmlLink;
                if (link != null)
                {
                    if (link.Href == url)
                    {
                        //Already added
                        return;
                    }
                }
            }
            HtmlLink cssLink = new HtmlLink();
            cssLink.Href = url;
            cssLink.Attributes.Add(“type”, “text/css”);
            cssLink.Attributes.Add(“rel”, “stylesheet”);
            Page.Header.Controls.Add(cssLink);
        }

The code is for the School MIS web parts I’m working on. The stylesheet is deployed to the layouts directory so we can reference it via the url above. You need to check to see if the link has already been added as usually there’s going to be more than one MIS web part on the page.
 

 

Richard Willis

Written by

Copyright © 2024 SalamanderSoft Limited