Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 890
Maxime Rouiller Avatar asked Apr 14 '10 20:04

Maxime Rouiller


People also ask

Can we change CSS file dynamically?

If you want to change the CSS styles dynamically you'll have to attach this portion of code to some event. For example, if you want to change the styles of your element when clicking on a button, then you have to first listen to the click event and attach a function containing the previous code.

What is dynamic CSS?

This is a collection of methods which give you the ability to query the stylesheets collection in a document, add and remove rules, and dynamically create new sheets.

Can we use CSS in asp net?

ASP.NET Web pages function as HTML pages at run time. You can therefore use cascading style sheets (CSS) to set the appearance of any elements on the page other than Web server controls.

How do I add a CSS page in Visual Studio?

In Solution Explorer, right-click the name of the Web site, and then click Add New Item. In the list of templates, select Style Sheet. In the Name box, type Layout. css, and then click Add.


2 Answers

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.

like image 74
paulH Avatar answered Oct 14 '22 08:10

paulH


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>
like image 27
Darin Dimitrov Avatar answered Oct 14 '22 07:10

Darin Dimitrov