By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,693 Members | 1,252 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,693 IT Pros & Developers. It's quick & easy.

Dynamically remove child controls ?

P: n/a
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.

Feb 10 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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
Feb 10 '06 #2

P: n/a
Hi Cor,

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

Regards,
Cerebrus.

Feb 10 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.