So i created a few picture boxes and rich text boxes during runtime and i want the user to be able to click 1 button to remove every single picture box or richtextbox. I've already tried a for each loop with me.controls and that doesn't work (leaves some behind and only removes 1 or 2) : Code: Dim c As Control For Each c In Me.Controls If (TypeOf c Is PictureBox) Then c.Dispose() End If Next For Each c In Me.Controls If (TypeOf c Is RichTextBox) Then c.Dispose() End If Next I really need a way to remove those objects, but that's all i got
Give this a try: Code: For Each c In Me.Controls If (TypeOf c Is RichTextBox Or TypeOf c Is RichTextBox) Then c.Visible = False Next It doesn't erase the Controls, but it hides them so that you may make them visible again later if you want If you want to remove the Controls completely, check out Me.Controls.Remove(c) where c is one of the controls (in the For-loop). Remember to set c to Nothing so that the Garbage Collector removes the unused object upon its next run.
Ok so setting the visibility to false is working how it should,but i really want to remove the control itself but that doesn't work how it should(same code as above, but replaced c.visible=false with me.controls.remove(c) and also tried c.dispose). I almost need a way to check if that control still exists then if it still exists try to remove it again and again untill it doesn't exist (I think it doesn't remove them all because it takes to long to remove them all and sort of times out in a sense)
I think I know why, we're trying to remove elements from a collection while at the same time looping over that collection. The enumerator doesn't like that very much One way to solve it is: Code: Dim list As List(Of Control) = New List(Of Control) For Each c In Me.Controls If (TypeOf c Is RichTextBox Or TypeOf c Is RichTextBox) Then list.Add(c) Next For Each c In list Me.Controls.Remove(c) Next This should theoretically speaking work
AHAH as usual u got it exactly right,works perfect...I feel like such a noob. Thanks for all your help man you solved all of my major problems in this program thanks
do you think it would be ok if i made a thread about some of the harder thing for me to learn for other people to see (like a centralized how-to guide). More advanced stuff of course like a snap to grid function and drawing to form and stuff like this and the idea of arrays and lists
Yeah I'm sure a lot of people would find that very useful. You could ask jlgager to link to your thread from his repository I think most people struggles a lot when they start doing custom drawing especially, so having a nice step by step guide would probably be most helpful.
ok that sounds like a good idea it'll be a while till i make my thread though(maybe 1 to 3 weeks) cuz i got other stuff 2 do