0

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);
meebee
  • 251
  • 1
  • 7
  • 17

1 Answers1

1

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

Community
  • 1
  • 1
Enrique Zavaleta
  • 2,098
  • 3
  • 21
  • 29
  • Sorry, I copied my code incorrectly. I edited it above but still arrive at the same errors. I saw that question before, but am wondering if there is any way to fix the error without having to go into the aspx pages. – meebee May 15 '15 at 17:48
  • Just with that code, I can't know what else could it be – Enrique Zavaleta May 15 '15 at 17:54