Adding StyleSheets Programmatically in Asp.Net

Posted by Braveyard on Stack Overflow See other posts from Stack Overflow or by Braveyard
Published on 2010-05-31T10:57:48Z Indexed on 2010/05/31 11:03 UTC
Read the original article Hit count: 382

Filed under:
|
|

I want to add StyleSheets programmatically in the head section but one of the examples I saw seemed to need to many lines of code to add just one style sheet even though I may need a lot:

Example Code:

HtmlLink css = new HtmlLink();
css.Href = "css/fancyforms.css";
css.Attributes["rel"] = "stylesheet";
css.Attributes["type"] = "text/css";
css.Attributes["media"] = "all";
Page.Header.Controls.Add(css);

I also use Page.Header.RenderControl() method but it didn't work either. Object null something error was thrown.

I also used Page.Header.InnerHtml and InnerText += "<link .... "/> things but they threw the Literal error which is I think common error.

I used this code :

List<Literal> cssFiles = new List<Literal>();
cssFiles.Add(new Literal() { Text = @"<link href=""" +   ResolveUrl("~/Resources/Styles/MainMaster/MainDesign.css") + @""" type=""text/css"" rel=""stylesheet"" />" });
cssFiles.Add(new Literal() { Text = @"<link href=""" + ResolveUrl("~/Resources/Styles/MainMaster/MainLayout.css") + @""" type=""text/css"" rel=""stylesheet"" />" });
AddStyleRange(cssFiles);

private void AddStyleRange(List<Literal> cssFiles)
{
   foreach (Literal item in cssFiles)
   {
     this.Header.Controls.Add(item);
   }
}

It worked at first but when I change the pages it stopped working.

I am using Master Page and I am writing these codes on Master.cs file and also some people recommended to use this.Header instead of Page.Header but when I built it throws an error which says I cannot declare that like this.

It shouldn't be that hard to add many styles.

It is getting complicated.

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET