2

Please consider the following:

code behind:

public void InitiateTable() 
{
    Controls.Add(new LiteralControl("<table class=\"table table-invoice\" >")); //Line that gave me error
    ...
    Controls.Add(new LiteralControl("</table>"));
}

on my ASP.Net page:

<% InitiateTable(); %>

When I run the code, it gives me an error saying:

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

Can someone please explain what I have done wrong? Thank you.

NewbieCoder
  • 676
  • 1
  • 9
  • 32
  • 1
    Possible duplicate of ["The Controls collection cannot be modified because the control contains code blocks"](http://stackoverflow.com/questions/778952/the-controls-collection-cannot-be-modified-because-the-control-contains-code-bl) – timothyclifford Dec 16 '15 at 09:08

3 Answers3

2

Note Changed LiteralControl to Control as suggested in comment.

You cannot modify the controls collection where the container contains <% %> code blocks as the error message tells you. Controls.Add will modify the controls collection. To get around this:

In your aspx page change

<% InitiateTable(); %>

to

<asp:Literal runat="server" id="mytable" />

then in your page load method, add a call to InitiateTable()

then in your InitiateTable() method change your code to something like this:

public void InitiateTable() 
{
    var literalControlValue = new StringBuilder();

    literalControlValue.Append("<table class=\"table table-invoice\" >"); 
    ...
    literalControlValue.Append("</thead>"));

    mytable.Text = literalControlValue.ToString();
}
DanL
  • 1,974
  • 14
  • 13
  • Hello, thanks for the reply, but I'm getting this error ` Unknown server tag 'asp:LiteralControl'..` Can I know why is this happening? Thanks in advance. – NewbieCoder Dec 16 '15 at 09:51
  • It's because LiteralControl is in the System.Web.UI namespace rather than the System.Web.UI.WebControls namespace like many other controls. Just add an appropriate tag prefix and the system.web.ui in your aspx page directives and it should work. – DanL Dec 16 '15 at 10:01
  • 1
    It should be `asp:Literal` rather than `asp:LiteralControl` – timothyclifford Dec 16 '15 at 10:09
0

Controls.Add(new LiteralControl("<table class='table table-invoice'>"));

timothyclifford
  • 6,799
  • 7
  • 57
  • 85
0

The issue is when you use Controls you are referencing the Page itself rather than the area you call InitiateTable.

If you're inserting controls into this area, this is what a Placeholder is for:

<asp:Placeholder id="phTable"></Placeholder>

Then in your Page_Load or some other event code:

private void Page_Load(object sender, System.EventArgs e)
{
    phTable.Controls.Add(new LiteralControl("<table class=\"table table-invoice\" >"));
    phTable.Add(new LiteralControl("</thead>"));
}
timothyclifford
  • 6,799
  • 7
  • 57
  • 85