Jayeet
Jayeet

Reputation: 11

Is there a way to put already created buttons into an array?

What I'm trying to do is put buttons I have already created into an array, however, whenever I look into the array it says that there is nothing in there? I was wondering if I'm doing something wrong.

Dim buttons As System.Windows.Forms.Button() = {Button1, Button2, Button3, Button4, Button5, Button6, Button7, Button8, Button9, Button10, Button11, Button12, Button13, Button14, Button15, Button16, Button17, Button18, Button19, Button20, Button21, Button22, Button23, Button24, Button25, Button26, Button27, Button28, Button29, Button30, Button31, Button32, Button33, Button34, Button35, Button36, Button37, Button38, Button39, Button40}

    Private Sub ClearBtn_Click(sender As Object, e As EventArgs) Handles ClearBtn.Click
    For i = 1 To 40
        buttons(i).BackgroundImage = System.Drawing.Image.FromFile("leaf.png")
    Next
End Sub

When the Clearbtn is clicked I get System.NullReferenceException: 'Object reference not set to an instance of an object.' And the array is empty. I've set the array to a global variable so it should work?

Upvotes: 0

Views: 132

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39122

I would store the background image at form level, and build the list in the Load() event like this:

Dim buttons As New List(Of Button)
Dim imgClear As Image = System.Drawing.Image.FromFile("leaf.png")

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For i As Integer = 1 To 40
        Dim ctl As Control = Me.Controls.Find("Button" & i, True).FirstOrDefault
        If Not IsNothing(ctl) AndAlso TypeOf ctl Is Button Then
            buttons.Add(DirectCast(ctl, Button))
        End If
    Next
End Sub

Private Sub ClearBtn_Click(sender As Object, e As EventArgs) Handles ClearBtn.Click
    For Each btn As Button In buttons
        btn.BackgroundImage = imgClear
    Next
End Sub

Note that searching for the buttons in this manner will find them no matter where they are. They don't have to be directly contained by the form, or even in the same containers.

Upvotes: 1

jmcilhinney
jmcilhinney

Reputation: 54417

The problem is that the code that creates your array is executed before the form constructor, so before all the child controls are created. Of course those fields are Nothing at that point. The solution is to declare the field where you are but to create the array and assign it to that field in the Load event handler.

Upvotes: 1

Related Questions