rage
rage

Reputation: 1837

2D array of labels

The following gives me a nullreference error. How can i accomplish this simple task while avoiding the error?

thanks!

Edit: L1,L2,etc are labels in my form.

Dim labelArray(,) As Label = {{L1, L2, L3, L4}, {L5, L6, L7, L8}, {L9, L10, L11, L12}, {L13, L14, L15, L16}}


private sub button_click(stuff that goes in here)
labelArray(zeroPoint.X, zeroPoint.Y).BackColor = Color.LimeGreen
end sub

EDIT: I got it to work by doing the following inside the form load method..

labelArray(0, 0) = Me.L1
    labelArray(0, 1) = Me.L2
    labelArray(0, 2) = Me.L3
    labelArray(0, 3) = Me.L4

    labelArray(1, 0) = Me.L5
    labelArray(1, 1) = Me.L6
    labelArray(1, 2) = Me.L7
    labelArray(1, 3) = Me.L8

    labelArray(2, 0) = Me.L9
    labelArray(2, 1) = Me.L10
    labelArray(2, 2) = Me.L11
    labelArray(2, 3) = Me.L12

    labelArray(3, 0) = Me.L13
    labelArray(3, 1) = Me.L14
    labelArray(3, 2) = Me.L15
    labelArray(3, 3) = Me.L16

Upvotes: 1

Views: 858

Answers (2)

John Woo
John Woo

Reputation: 263733

Try this,

Dim labelArray(,)
Private Sub button_click(stuff that goes in here)
    labelArray = New Label(,) {{l1, l2, l3, l4}, {l5, l6, l7, l8}, {l9, l10, l11, l12}, {l13, l14, l15, l16}}
    labelArray(zeroPoint.X, zeroPoint.Y).BackColor = Color.LimeGreen
End Sub

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415880

Your label array initializer runs before the InitializeComponent() method, where all your labels are instantiated. You are effectively adding a bunch of null references to the array.

Leave the array declaration where it is, but move the assignment code to the end of the form's constructor, and I think that will fix the problem.

Beyond that, you'll need to check the zeropoint.X and zeropoint.Y result in valid indexes. Remember that, by default, vb.net indexes work a little different than either C# or VB6.

Upvotes: 2

Related Questions