Search code examples
arraysvb.nettextbox

Grouping Controls into an array and accessing their properties


I have an array in the scope of the class form1

Dim ArrayTextBoxes() as Textbox = new Textbox() {textbox1, textbox2}

And a matching length array of labels

Dim ArrayLabels() as Label = new Label() {label1, label2}

I want to (in a function belonging to the form1 class):

For i = 0 to ArrayTextBoxes.Count - 1
    ArrayTextBoxes(i).Enabled = True
    ArrayTextBoxes(i).ReadOnly = True
    ArrayTextBoxes(i).BackColor = Color.Gray
    ArrayLabels(i).BackColor = Color.Gray
Next

But ArrayTextBoxes(i) returns Nothing

I also need this to work for ComboBox() and CheckBox()


Solution

  • Presumably those are member variables rather than local, i.e. declared at class level rather than in a method. If that's the case then, for one thing, you should use Private rather then Dim. As for the issue, it's because that code is executed before the constructor is executed and so the controls haven't been created yet. You need to declare the variables where you are but create the arrays and assign them to those variables in the Load event handler, e.g.

    Private textBoxes As TextBox()
    
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        textBoxes = {TextBox1, TextBox2}
    End Sub