Dynamically remove child controls ?

C

Cerebrus99

Hi all,

I am dynamically removing some child controls from a groupbox. The problem
occurs because
some controls are removed and some aren't.

Dim ctl as Control
For each ctl in GroupBox1.Controls
If CStr(ctl.Tag) = "Removable" Then
GroupBox1.Remove(ctl)
End If
Next

After much debugging, I realized that when a Control is removed from the
control collection, all
subsequent controls are moved up one position in the collection.

For instance, if I have 4 such removable controls, then this code results in
only 2 being removed.
(The first and the 3rd in the collection.) I have understood why this is
happening, and could draw a
diagram to explain it, but I can't think of a workaround, other than
hard-coding the index nos. of
the controls. I need to remove all 4 of the controls.

Basically, what happens is that when ChildControl(0) is removed, the
remaining 3 controls get moved up in index no. So, ChildControl(1) now
becomes ChildControl(0). My loop moves to the next control (ChildControl(1))
and deletes the 3rd control in original collection. It gives an error in the
next round, since ChildControl(2) does not exist anymore.

There *must* be a pretty way to do this !

Any help would be appreciated.

Regards,

Cerebrus.
 
C

Cerebrus99

Hi Cor,

LOL ! Trust me to miss something so obvious ! Thanks a lot ! It works now.

Regards,
Cerebrus.
 
C

Cor Ligthert [MVP]

Cerebrus,

Because of this problem I use for removing from a collection, even if it is
not selective, the method to do it bottomwards up.

\\\
For i as integer = GroupBox1.Controls.Count - 1 to 0 step -1
dim ctl as Control = GroupBox1.Controls(i)
If CStr(ctl.Tag) = "Removable" Then
GroupBox1.Remove(ctl)
End If
Next
///
typed here so watch typos or whatever.

I hope this helps,

Cor
 

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

Top