views:

371

answers:

3

How would I register a Style Sheet on the Master Page within a SharePoint Web Part. In other words how would I add a CSS link on the master page, at run time, and the code which does this is present in a custom web part.

I do not want to change the Master Page directly.

I could not see anything in the API (this.Page.Master) which would help me.

Thanks for your help.

+2  A: 

Hi,

What you're looking for is quite tricky to achieve because you would have to :

  • retrieve the master page markup
  • include the in the programmatically using regex
  • push the modified markup back to the server again

I would suggest you a work around wich is easier to achieve : use a base class for all your webparts and add the following code in this webpart :

Microsoft.SharePoint.WebControls.CssRegistration.Register("/.../mystyles.css")

I understand that It's a bit intrusive but this would save you some hard time of debugging.

Manitra.

Manitra Andriamitondra
I usually use this too, or through a Page.ClientScript.RegisterClientScriptBlock. Why would it be intrusive, seems like a standard ASP.NET thing to do?
ArjanP
It's intrusive because : - all your webpart must inherits from the same base class- if you have have some webpart pages without any webpart of yours, the stylesheet won't be addedBut, it's the way I include Css with sharepoint and indeed it works :)
Manitra Andriamitondra
+2  A: 

The standard sharepoint master pageshave the following placeholder in the head section:

<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server"/>

In your webpart you could:

var placeholder= Page.FindControl("PlaceHolderAdditionalPageHead");
var cssLink = new Literal();
cssLink.Text = "<link .... />";
placeholder.Controls.Add(cssLink);
Michael Edwards
A: 

There's the HTMLLink class you can use to dynamically add a CSS page reference to your masterpage.

Look here:http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmllink.aspx

If you want to do it from inside your webpart, I guess you'd need a reference to the parent.

Tony