meebee
meebee

Reputation: 261

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

I am trying to dynamically add an ASP LinkButton control to my page but come across the error "The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)".

Is there any workaround for this by making a change in the code behind? I have seen fixes for this that would change the client side script but I need to fix this from the code behind. I am adding this control to a base page which many pages inherit. Therefore, it would be ideal to make this change in the code behind rather than changing each individual aspx page.

Code below is how I added the control to my pages.

Edited:

            LinkButton addLinkButton = new LinkButton();
            addLinkButton.ID = "linkButton";
            addLinkButton.PostBackUrl = "Default.aspx";
            this.Form.Controls.Add(addLinkButton);

Upvotes: 0

Views: 845

Answers (1)

Enrique Zavaleta
Enrique Zavaleta

Reputation: 2098

Your code is not working because you need to create a variable, you can't assign values to a type. The following code works for me, if the error persist, it means that it could be something else.

Replace your code with this one

LinkButton lbtn = new LinkButton();
lbtn.ID = "linkButton";
lbtn.Text = "my new LinkButton";
lbtn.PostBackUrl = "Default.aspx";
this.Form.Controls.Add(lbtn);

also, look at this question, maybe there you can find the answer, let me know if it works

Upvotes: 1

Related Questions