10

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.

1
  • At what point during the page life cycle are you trying to access the Page.Header? Commented Apr 14, 2010 at 20:18

4 Answers 4

21

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Got it. I was missing the Runat="Server" in the header tag of my masterpage. :) Thank you!
Wouldn't this be a problem if you added the control, say, 10 times on your page? Then the CSS file would be linked 10 times.
@Peter, yes I guess that would be problematic.
11

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.

Comments

1

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

1 Comment

exactly if you adding dynamic url, the it won't work in head tag
1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.