Welcome to Idea R | Branding - Web Agency - Digital Strategies
Switch to the mobile layout

      Idea R - Do others know who you are? Design your corporate identity

Blog

Take a software geek from the 80s, add a new generation graphic designer and dilute with a longtime marketing strategist. Shake vigorously and you'll get the Idea R's blog.

Change language... italiano

How to include CSS files programmatically in ASP.NET

Published on 7/31/2012
Categories: Web Design
How to include CSS files programmatically in ASP.NET

ASP.NET gives you the opportunity to add script blocks and JavaScript includes at runtime using methods like ClientScriptManager.RegisterClientScriptInclude().

How to perform a similar action to include style sheets?

There's no native method, but it's quite simple to perform: we're going to use the HtmlLink control.

HtmlLink link = new HtmlLink();
link.Href = "./MyFolder/MyStyleSheet.css";
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
Page.Header.Controls.Add(link);

An interesting parameter of the ClientScriptManager.RegisterClientScriptInclude() method is the Key, that's used to assure you do not add the same include twice.

How to perform the same thing with the previous code?
The solution is to give the control a unique id:

public void AddStyleLink(String Key, String StyleUrl)
{
    if (!String.IsNullOrEmpty(Key))
        if (Page.Header.FindControl(Key) != null) return;
 
    HtmlLink link = new HtmlLink();
    if (!String.IsNullOrEmpty(Key)) link.ID = Key;
    link.Href = StyleUrl;
    link.Attributes.Add("type", "text/css");
    link.Attributes.Add("rel", "stylesheet");
    Page.Header.Controls.Add(link);
}

 

Did you find this article useful?

Please help us to spread it over the web using Twitter.
You have only to press the button here below!

You are the reader number 8,727.

Comments

Previous article

Previous article

Google Tag Manager: stop sinking into scripts

Next article

Internal campaigns with Google Analytics and .NET AdRotator

Next article

Scroll to top