Reputation: 328
For practice I am writing a VB application which simulates and elevator system with 4 elevators and 40 floors in the building - when a button is pressed I want it to change color until the elevator reaches that floor.
Currently the only way I can think of to do this is by hard-coding a check which looks through the list of destination floors that each lift has and if it contains a given floor change the color of that button like this:
' button 1
If elevator1.goingUpList.Contains(1) Or elevator1.goingDownList.Contains(1) Then
lift1Button1.BackColor = Color.LightGoldenrodYellow
ElseIf (elevator1.goingUpList.Contains(1) = False) Or (elevator1.goingDownList.Contains(1) = False) Then
lift1Button1.BackColor = DefaultBackColor
End If
The problem is with this is that I would have to do it for each button (40 in total) of each of the 4 elevators - 160 times essential 960 lines to do a fairly simple task. THere must be an easier way?
I was thinking a loop that goes through the elevators lists , retrieving each floor that is in the list could be an easier solution - but how would I get the corresponding button to change color?
Upvotes: 0
Views: 3299
Reputation: 2119
Yes you can use For Each
loop for your buttons. Windows Forms have the Controls
Collection
property. Every control such as Button
, Label
and TextBox
are added to that Contorls
Collection
unless you are using Panel
, GroupBox
or other containers.
By using For Each
loop in Me.Controls
, all type of controls will be going through. So you have to check for the type of control with TypeOf
operator.
If your form has other buttons rather than "Elevator buttons", you need to set Tag
property of your "Elevator buttons" to "1" or elevator number.
Here is the sample code
Dim ctl As Object
Dim elevatorNumber As String
Dim buttonNumber As String
For Each ctl In Me.Controls
If TypeOf ctl Is Button Then
elevatorNumber = ctl.Tag
buttonNumber = ctl.Text
If elevatorNumber = "1" Then
If elevator1.goingUpList.Contains(buttonNumber) Or elevator1.goingDownList.Contains(buttonNumber) Then
ctl.BackColor = Color.LightGoldenrodYellow
ElseIf (elevator1.goingUpList.Contains(buttonNumber) = False) Or (elevator1.goingDownList.Contains(buttonNumber) = False) Then
ctl.BackColor = DefaultBackColor
End If
End If
End If
Next
Upvotes: 1