Adding a CSS Stylesheet to a Web Part

09 November, 2015 · less than a minute to read

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.

        ///<summary>Adds the stylesheet to the page.</summary>
        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 headshot

Written by Richard Willis

Managing Director / Founder

Richard started SalamanderSoft in 2007 after a successful career as a software developer. Wanting to start his own company and with experience in integrating school systems he set out to build the best integration system for schools and to exceed customer expectations. He starting out on his own, doing all the coding, support and sales until finally the growing number of customers meant he needed to start growing the team. He is still heavily involved in coding the core Integration Suite product in addition to running the company and being the first point of contact for prospective customers.

Copyright © 2020 SalamanderSoft Limited