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.
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)
HtmlLink cssLink = new HtmlLink();
cssLink.Href = url;
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.