Dynamically looping through picture box controls in Visual Basic 2010 does not seem to follow any order

Dean picture Dean · Jan 2, 2013 · Viewed 8k times · Source

In a Visual Basic 2010 form application I have the below code snippet:

For Each ctlControl In Me.Panel1.Controls
    If TypeName(ctlControl) = "PictureBox" Then
        ctlControl.image = Nothing
    End If
Next ctlControl

My problem is when it loops through the controls it does not start with the top left control and it seems to go over each picture box in random order.

How do I control the order of which picture box is updated next. Is there a property similar to tab index(in VB 6) which I can manipulate to control the order in which picture boxes are updated by my loop?

Answer

theGD picture theGD · Jan 2, 2013

As a more proper and sure way, I would get each picture box, keep handles and locations of them, then sort them according to their location. Now they are ready to use. Here is an example:

Public Class Form1
    Structure Pbox
        Dim handle As IntPtr
        Dim top As Integer
        Dim left As Integer
    End Structure
    Dim pboxlist As New List(Of Pbox)
    Sub ClearImages()
        pboxlist.Clear()
        For Each c As Control In Me.Controls
            If TypeName(c) = "PictureBox" Then
                Dim x As New Pbox
                x.top = c.Top
                x.left = c.Left
                x.handle = c.Handle
            End If
        Next
        pboxlist.OrderByDescending(Function(a) a.top).ThenByDescending(Function(a) a.left)
        For Each item In pboxlist
            Dim x As PictureBox = PictureBox.FromHandle(item.handle)
            x.Image = Nothing
        Next
    End Sub
End Class

Another approach is using a good naming, so that you can use their names to sort them. For instance, PictureBox1 will come before PictureBox2 if you sort. So you should use PictureBox1 for the very top and left one and PictureBox2 for the next one and so on...

EDIT: Using Tag property, as John Bustos suggested, instead of names is an easier and better idea. So without getting lost in names, you can sort picture boxes according to their Tags which are defined by you.