Controls disappear after postback when added to a controlcollectio

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I run into a problem where an ASP CheckBoxList control disappears after being
added to a controlcollection. (Have not tested this with other Controls ...)

It takes a WebForm with 3 lines of codes to reproduce the behaviour

Create a WebForm with a CheckBoxList and a Linkbutton. Add a few items to
the list, and add the following code to the LinkButton Click event:

Dim MyctrlCollection As ControlCollection
MyctrlCollection = Me.CreateControlCollection()
MyctrlCollection.Add(FindControl("CheckBoxList1"))

See how the CheckBoxList is gone, after clicking the LinkButton. I have no
idea why it is not rendered anymore ... Please can someone explain?
(Viewstate is Enabled!)

If you add it to e.g. an ArrayList, everything works as expected.
 
Note A Control object can only be assigned to one Control.ControlCollection
at a time. If the Control is already a child of another control it is removed
from that control before it is added to another control.
(From MSDN documentation).

It would be interesting to know the reason why. My guess is has something
to do with reference passing versus pass by value.
 
From MSDN documentation on Controls.ControlCollection.Add

Note A Control object can only be assigned to one
Control.ControlCollection at a time. If the Control is already a child of
another control it is removed from that control before it is added to another
control.

I wouldn't mind knowing the definitive reason why.
 
Note A Control object can only be assigned to one Control.ControlCollection
at a time. If the Control is already a child of another control it is removed
from that control before it is added to another control.
 
From MSDN documentation on Controls.ControlCollection.Add

I have been looking for such a piece of text ... well, then it IS
documented. Thanks for pointing me to the docs. I haven't found anything
llike that in the .NET help files. All I see in the docs is: Adds the
specified Control object to the collection.

Also, it is just something I did not expect. After all, a control collection
(I thought) is just another collection specially for controls. But as you
already suggest, there's probably more to it ...


Martin
 
No problem Martin. I suspect the same but haven't used the ControlCollection
much. Thanks for the training :)!
 
Back
Top