Maxime Rouiller
Maxime Rouiller

Reputation: 13699

Dynamically adding a CSS file from an ASP.NET Server Control

I have a custom control and I want to dynamically insert a link to a stylesheet.

Might not be the best solution of the year but it needs to be done. Any idea how to do it?

Everytime I try, Page.Header is null.

Upvotes: 10

Views: 11946

Answers (4)

raw_hitt
raw_hitt

Reputation: 989

I know this question have already accepted an answer. I recently went through the same error. The javascript/Css with <% %> tags from the head can give you error. Removing ASP tags <% %> from head fixes this error.

I was getting the same error in a weird way, I had css files in master page, It used to work for the first page but on the second page after redirecting, I was getting error. So I removed the css link from head tag and pasted it at the end of form tag.

http://italez.wordpress.com/2010/06/22/ajaxcontroltoolkit-calendarextender-e-strana-eccezione/

Upvotes: 1

Siddharth Sharma
Siddharth Sharma

Reputation: 21

If you are dynamic css in head tag it wont work, you need to paste the css link tag in the body tag then it may work

Upvotes: 1

paulH
paulH

Reputation: 1132

To avoid the problem of multiple stylesheets when adding the control 10 times to the page, change the above code slightly:

string styleSheet = "stylesheetName.css";
if (this.Page.Header.FindControl(styleSheet) == null)
{
    HtmlLink cssLink = new HtmlLink();
    cssLink.ID = styleSheet;
    cssLink.Href = "~/styles/" + styleSheet;
    cssLink.Attributes.Add("rel", "stylesheet");
    cssLink.Attributes.Add("type", "text/css");
    this.Page.Header.Controls.Add(cssLink);
}

By giving the control an ID you can check if it already exists, and so ensure that you only add it the once.

Upvotes: 11

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Here's how you would normally add a CSS programatically:

protected void Page_Init(object sender, EventArgs e)
{
    var link = new HtmlLink();
    link.Href = "~/styles/main.css";
    link.Attributes.Add("rel", "stylesheet");
    link.Attributes.Add("type", "text/css");
    Page.Header.Controls.Add(link);
}

You might need to put a runat="server" in the head tag:

<head runat="server">
    <title>Add CSS example</title>
</head>

Upvotes: 21

Related Questions