Programmatically add a CSS link on your WebPart

by Oscar 2. September 2009 11:17

So, you have a WebPart you have developed and you are deploying it as part of a Solution (at least you should be).  Your WSP includes CSS, Images and other artifacts that are dropped into the _layouts folder when your featureis activated.

Now you need a way to ensure that the CSS Classes you are referencing on your WebPart code are available to the WebPart, BUT you do not want the person deploying the WebPart to modify the Master Page.  In other words, your WebPart should not have any dependencies outside of your Solution.

There is a way to simply add a CSS link within code.  You can use the Class available on the Object Model

protected override void CreateChildControls()
{
    Microsoft.SharePoint.WebControls.CssLink cssLink = new Microsoft.SharePoint.WebControls.CssLink();
    cssLink.DefaultUrl = "/_layouts/MyAppFolder/CSS/tabBasic.css";

    this.Page.Header.Controls.Add(cssLink);

more code………

Simple yet effective!

-Oscar

Tags:

MOSS 2007 | WSS 3.0

Comments

11/26/2009 6:54:59 PM #

Hi there Oscar,

Very nice post, but I wonder if you can give a hand, I am trying to set a custom master page to a webapp, but my custom page uses some css and a .aspx file, but I wonder how could I add the files to each list, I can upload the master page, but I do not know how to add the another files or if this have to be placed in a specific folder.  Any suggestion???

Regards
Nelson

Nelson Guatemala | Reply

1/1/2010 10:43:53 PM #

Nelson, let me know if you still need help...

Oscar United States | Reply

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About Oscar

Oscar Medina - SharePoint Solutions Architect

I am a SharePoint Solutions Architect and Managing Partner at SharePointAce Consulting Group, LLC.  I have over 13 years of software development experience. 

Previously a Consultant at Microsoft Consulting Services (MCS) North West Region with focus on the SharePoint Products and Technologies Platform.  I have been involved with SharePoint since it's first version (SharePoint 2001) and have grown more gray hair providing solutions ever since :)

Author of the CQWP – Recurring Calendar Events at http://cqwprce.codeplex.com

 

Follow SharePointAce on Twitter! Follow me on Twitter.


Contributor to the book:

 

Occasional Speaker at SharePoint Saturday - SharePoint Saturday

RecentComments

Comment RSS