Dynamically Add Stylesheet in ASP.NET

9. July 2009
I was trying to dynamically change the stylesheet in an asp.net application and ran into the following problem error: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Here was my code in the Page_Init

 HtmlLink cssLink = new HtmlLink();
 cssLink.Href = "test.css";
 cssLink.Attributes.Add("rel", "stylesheet");
 cssLink.Attributes.Add("type", "text/css");
 this.Page.Header.Controls.Add(cssLink);


This would seem to work, but after a bit of searching on the internet here is what was causing my problem.

In the <head> tag of the aspx page I have a <script type="javascript"> tag with the following code in it:

var gvControl = document.getElementById('<%= this.gvFreeze.ClientID %>');

All I had to do was switch the "=" to a "#" and all was good.  Seems simple enough right? Guessed I shouldn't have assumed :)


Here is a good article explaining this as well:

http://www.west-wind.com/weblog/posts/5758.aspx

So in the end I had the correct code to dynamically change the stylesheet for the aspx page, but it was my javascript that was messing it all up. Happy coding...
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

ASP.NET

blog comments powered by Disqus