English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have 100 buttons forming a 10 X 10 grid.

When I click Button100 I want every button's backColor to change to Black.

The only way I know how to do this, is to start listing them one at a time:

Private Sub Button100_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button100.Click

Button1.backColor = color.black
Button2.backColor = color.black
Button3.backColor = color.black

... etc etc until you get to Button100 ... but this method takes up loads of CPU and I know there is an easier way ... I'm just too new at VB.

Is there a way I can simply denote (Button1 THROUGH Button100). backColor = color.black ?

Thank you so much for any help!

2007-06-26 11:36:09 · 3 answers · asked by djdeity25 1 in Computers & Internet Programming & Design

3 answers

You can use the Form's Controls Collection and a For Each loop to iterrate through each object on a form. When a button is extracted from the collection (determined by an IF) the object is assigned to a Button variable which will expose the buttons background propert which may then be set to what ever color

Dim btn As New Button
For Each obj As Object In Me.Controls
If obj.GetType.ToString.Equals(btn.GetType.ToString) Then
btn = obj
btn.BackColor = Color.Black
End If
Next

This code will set ALL buttons on the form to black. If you do not want specific buttons to be colored you can use the TAG property to hold a Key value

Using another if statement you can examine the TAG property to determine if the button should be changed or set to a particular color...

Dim btn As New Button
For Each obj As Object In Me.Controls
If obj.GetType.Equals(btn.GetType) Then
btn = obj
if btn.tag = "BLK" THen
btn.BackColor = Color.Black
end if
End If
Next

2007-06-26 14:48:12 · answer #1 · answered by MarkG 7 · 0 0

You can use an array of buttons instead.
Create one button and then copy and paste it. VB will ask you if you want to create an array and then all the buttons will have the same name with an index. Eg Button(0), Button(1).
Optional, you can do that in the code. Create just one button and set the Index property to 0. Then, in the form load event use load to create the others. Eg Load Button(1). Use a for loop, don't type all the lines. You can use for loops to arrange them in the form and change any property you want.

2007-06-26 11:46:38 · answer #2 · answered by Anonymous · 1 0

i don't know, sorry.

2007-06-26 11:43:11 · answer #3 · answered by Packerfan22 4 · 0 1

fedest.com, questions and answers