Adding StyleSheets Programmatically in Asp.Net

Okay, here is the solution I am currently using :

I created a helper class :

using System.Web.UI;
using System.Web.UI.WebControls;

namespace BusinessLogic.Helper
{
    public class CssAdder
    {
        public static void AddCss(string path, Page page)
        {
            Literal cssFile = new Literal() { Text = @"<link href=""" + page.ResolveUrl(path) + @""" type=""text/css"" rel=""stylesheet"" />" };
            page.Header.Controls.Add(cssFile);
        }
    }
}

and then through this helper class, all I have to do is :

CssAdder.AddCss("~/Resources/Styles/MainMaster/MainDesign.css", this.Page);
CssAdder.AddCss("~/Resources/Styles/MainMaster/MainLayout.css", this.Page);
CssAdder.AddCss("~/Resources/Styles/Controls/RightMainMenu.css", this.Page);
//...

So I can add as much as I want with one line of simple code.

It also works with Masterpage and content page relationships.

Hope it helps.

P.S: I don’t know the performance difference between this and other solutions but it looks more elegant and easy to consume.

Leave a Comment