Samoop
Samoop

Reputation: 51

How to group multiple buttons as 'one'

I'm new to coding, and for a project I need to write alot of these 'blocks', usually a letter and number followed by a statement to enable, or disable them:

a1.Enabled = True
a2.Enabled = True
a3.Enabled = True
a4.Enabled = True
a5.Enabled = True
a6.Enabled = True
a7.Enabled = True
a8.Enabled = True
a9.Enabled = True

I've looked around for any ideas or help, but nothing seems to work, all I want to try and do is have one line eg.

    ablock.Enable = False

or anything similar.

Thank you for your help.

Upvotes: 0

Views: 368

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 415790

You want an array defined as a member of the class, like this:

Private aBlock() As Button

Then somewhere early on, as the page or form loads and after the controls have actually been created, you want code like this:

aBlock = {a1, a2, a3, a4, a5, a6, a7, a8, a9}

The form designer makes it awkward to declare the controls using an array in the first place, but you can at least put them all in the same collection as the form/page loads.

Later, that will let you run code like this:

For Each btn As Button In aBlock
    btn.Enabled = True
Next

Alternatively, if these Buttons already belong to some common container, like a Panel or GroupBox, and assuming WinForms, you can do this:

For Each btn As Button In Panel1.Controls.OfType(Of Button)()
    btn.Enabled = True
Next

Upvotes: 2

laancelot
laancelot

Reputation: 3207

Coehoorn has the nicest way to do it, but as a beginner you might want the easiest one instead, so I'll give it to you.

You can make a Sub do it in your place, so you don't have to write all the buttons names all the time.

here's a way you could do it:

Private Sub SetABlockEnabled(ByVal isEnabled As Boolean)
    a1.Enabled = isEnabled
    a2.Enabled = isEnabled
    a3.Enabled = isEnabled
    a4.Enabled = isEnabled
    a5.Enabled = isEnabled
    a6.Enabled = isEnabled
    a7.Enabled = isEnabled
    a8.Enabled = isEnabled
    a9.Enabled = isEnabled
End Sub

Now you can manage the whole block all at once:

SetABlockEnabled(True)

Upvotes: 1

Related Questions