Pages

Search This Blog

Thursday, November 1, 2007

Dynamic CSS reference in ASP.NET

This sample allowed me to dynamic add CSS link to my ASP.NET page. If css provided via querystring, the page will link to provided css. If not provided then if will refer to the default css.


protected void Page_Load(object sender, EventArgs e)
{
string mycss;

if (Request.QueryString["mycss"] != null)
{
if (Request.QueryString["mycss"].ToString().Trim().Length > 0)
{
mycss= Request.QueryString["mycss"].ToString().Trim();
}
else
{
mycss= "~/default.css";
}
}
else
{
mycss= "~/default.css";
}
AddLinkedStyleSheet(this, mycss);
}

public static void AddLinkedStyleSheet(Page page, string stylesheet)
{
HtmlLink link = new HtmlLink();
link.Href = page.ResolveUrl(stylesheet);
link.Attributes["text"] = "text/css";
link.Attributes["rel"] = "stylesheet";
page.Header.Controls.Add(link);
}

credit give to
Rich Sturim

1 comment:

Bradley said...

Thanks for this article, worked a treat.