Creating a new control collection

S

Scott A

I have an aspx page that has many nested controls. For example I have
Panels that contain text boxes. There is also text boxes on the page
itself. I'd like to loop through every control on the page and build a
collection of those controls that interest me (in this case the text
box controls). I can get at the controls by doing:

foreach (Control c in this.Controls)

As I come accross those controls I want I'd like to add them to my new
control collection. I've tried creating a new collection like this:

System.Web.UI.ControlCollection cc = CreateControlCollection();

Everytime I try to add a control to this collection I get this error:

"The list that this enumerator is bound to has been modified. An
enumerator can only be used if the list doesn't change."

How can I create a control collection that I can add controls to?

TIA,
Scott
 
V

Victor Garcia Aprea [MVP]

Hi Scott,

What you're seeing is okay. You can't use an enumerator if the list is
modified. When you actually add the control to your new control collection,
the control is automatically being removed from the old control collection
and then added to the new one. This causes the old control collection to get
modified (it now has fewer controls) and you get the mentioned exception.

Note that you can't have a single control added to two ControlCollection at
the same time because a control can't have more than one "parent" at the
same time.

--
Victor Garcia Aprea
Microsoft MVP | ASP.NET
Looking for insights on ASP.NET? Read my blog:
http://obies.com/vga/blog.aspx
To contact me remove 'NOSPAM'. Please post all questions to the newsgroup
and not by private mail.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top