James
James

Reputation: 31738

How to remove controls with runat="server" specified in asp.net

I have a webpage with server accessible controls, see 'FileIconLink' below:

<body>
    <p class="FirstTitle style5">Downloads:</p>
    <div id="BreadcrumbDiv">
        <p style="padding-left:5px; ">Page Loading...</p>
    </div><!--/BreadcrumbDiv-->
    <div id="DirLinksDiv">
        <p><span class="SecondTitle">Files:</span></p>
            <a runat="server" href="#" id="FileIconLink">File</a>
            <% WriteFileLinks(); %>
        <p><span class="SecondTitle">Folders:</span></p>
            <a runat="server" href="#" id="FolderIconLink">Folder</a>
    </div><!--/DirLinksDiv-->
</body>
<%RemoveHTMLTemplates(); %>

Both 'FileIconLink' and 'FolderIconLink' are templates of web controls which are copied by my code - such as <% WriteFileLinks(); %> above. How could these templates be permanently removed from the web page at run-time on the server without causing the error:

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

Thanks in advance!

Upvotes: 0

Views: 1128

Answers (4)

jayprakash
jayprakash

Reputation: 49

The Page object has another function apart from Page_Load function called Page_PreRender, this function gets executed before Page_Load. So please try remove logic in this Page_PreRender function. Please refer this link http://msdn.microsoft.com/en-us/library/system.web.ui.control.prerender.aspx

Upvotes: 1

James
James

Reputation: 31738

Ultimately I realised my approach was wrong, as Cade Roux was alluding to, I needed to make up my mind where the templates were going to be used.

My solution was as follows:

  • Make controls for containing the results of my (previously inline) code.
  • Use templates in Page_Load to fill the controls described above.
  • Delete templates in Page_Load.
  • Do nothing inline.

Upvotes: 1

John
John

Reputation: 695

This is because you have <% %> inside the control you're trying to change. Instead of using <% %> in the aspx page, I would modify the code behind to add a literal control or something to the div, like:

DirLinks.Controls.Add(new LiteralControl(WriteFile()));

You should then be able to modify your control form the code behind.

Upvotes: 3

Cade Roux
Cade Roux

Reputation: 89651

Your inline code is executed during render.

But you probably want to get rid of the templates during Load.

Which means that the two techniques conflict.

Upvotes: 2

Related Questions