Friday 9 November 2012

The Controls collection cannot be modified because the control contains code blocks ((i.e. <%..%>)).

I am trying to add css file reference to the head section of the master page from code behind as follows.

// CSS

HtmlLink link = new HtmlLink();

link.Href = "../Styles/MyCSS.css";

link.Attributes.Add("rel", "stylesheet");

link.Attributes.Add("type", "text/css");

// Need this because we're in a master page

Control headControl = Page.Master.FindControl("head");

if (headControl != null)

{

headControl.Controls.Add(link); // Add css to header

}

But I got the below error at run time.

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

There are 2 solutions :

1. This link contains the actual solution :

http://www.dotnetboss.com/2010/09/27/the-controls-collection-cannot-be-modified-because-the-control-contains-code-blocks-i-e/

But I don’t know how to add data binding expressions from code behind.

2. Add this css file to the html body.

This worked for me.

Code now changed to:

// CSS

HtmlLink link = new HtmlLink();

link.Href = "../Styles/MyCSS.css";

link.Attributes.Add("rel", "stylesheet");

link.Attributes.Add("type", "text/css");

Page.Master.Controls.Add(link);

// Need this because we're in a master page

//Control headControl = Page.Master.FindControl("head");

//if(headControl != null)

//{

// headControl.Controls.Add(link); // Add css to header

//}