Not Sure How To Do A Control Array Or Pass An Object To A Sub

zunebuggy65

Active member
Joined
Oct 12, 2023
Messages
42
Programming Experience
3-5
I have a grid made up with many PictureBoxes Named C0 through C503. I could have used several GroupBoxes as well. I have a routine that changes the BackColor of each based on a huge Select Case statement and KeyDown event for each arrow key. This works and makes it look like a cursor showing the current position based on the arrow keys.

The problem is that it's very slow. Instead of using the huge Select Case to clear and set the "cursor", is there are better way? I tried passing "C" & n (the name of each PictureBox ) to a Sub and this caused an exception.

VB6 used to let you make a control array for PictureBoxes or GroupBoxes like picBox(x) to reference each one, but I do not see that option in VB.net.

Thank you
 
There's Controls("name") or Controls(index)
 
I have a grid made up with many PictureBoxes Named C0 through C503.
You probably ought to put all your controls in a TableLayoutPanel. You can get the column and row indexes of the current control and then get the next control simply by incrementing or decrementing the appropriate index.
 
As a super basic example of using the controls object. I put seven labels on a form Label1 ... Label7. Then using the KeyDown event of the form cycled through the labels changing the background color. (KeyPreview must be set to True)

This is ultra simplistic of course.

Cycle through labels:
Public Class Form1
    Dim currentLabel As Integer
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        currentLabel = 0
    End Sub

    Private Sub HighlightLabel()

        Dim lbl As Label = Me.Controls($"Label{currentLabel}")
        lbl.BackColor = Color.Yellow

    End Sub

    Private Sub ResetLabel()

        Dim lbl As Label = Me.Controls($"Label{currentLabel}")
        lbl.BackColor = Color.Transparent

    End Sub

    Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
        Select Case e.KeyCode
            Case Keys.Down
                ' move the highlight to the next label down
                If currentLabel > 0 Then
                    ResetLabel()
                End If

                currentLabel += 1
                If currentLabel = 8 Then currentLabel = 1

                HighlightLabel()

            Case Keys.Up
                ' move the highlight to the previous label down
                If currentLabel > 0 Then
                    ResetLabel()
                End If
                
                currentLabel -= 1
                If currentLabel = 0 Then currentLabel = 7
                
                HighlightLabel()

        End Select
    End Sub
End Class
 
Back
Top