Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

For Each Statement doesn't access all controls

Status
Not open for further replies.

WomanPro

Programmer
Nov 1, 2012
180
GR
Hello everyone,
I am having a picture box on my form named pb and I am adding buttons through runtime, however I need a process for removing all buttons that belong to the pb collection, but for each statement removes one less object-button. Any suggestions please??? Any help would me much appreciated. Thank you so much in advanced.

Public Class Form1
Dim Btn1 As New Button
Dim btn2 As New Button
Dim btn3 As New Button
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Btn1.SetBounds(100, 200, 76, 27)
Btn1.Name = "button1"
btn2.BackColor = Color.Aqua
btn2.SetBounds(50, 100, 76, 27)
btn2.Name = "button2"
btn3.BackColor = Color.Green
btn3.SetBounds(300, 100, 76, 27)
btn3.Name = "button3"
pb.Controls.Add(Btn1)
pb.Controls.Add(btn2)
pb.Controls.Add(btn3)
End Sub

Private Sub Remove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Remove.Click
For Each obj As Button In Me.pb.Controls
pb.Controls.Remove(obj)
Next


End Sub
 

This will remove all the buttons in the picture box:

Code:
For i As Integer = PictureBox1.Controls.Count - 1 To 0 Step -1

    If TypeOf PictureBox1.Controls(i) Is Button Then

        PictureBox1.Controls.Remove(PictureBox1.Controls(i))

    End If

Next

I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
The problem with the original code was that "pb.Controls" is a collection. You want to avoid modifying a collection as you're walking through it in a for/each loop or you end up with unexpected results, as you saw.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top