如何在同一时间更改每个52标签的背面颜色

时间:2015-10-14 09:15:04

标签: vb.net visual-studio visual-studio-2013

如图所示,我想每次点击一把椅子(绿色方块),我想把背面颜色改为棕色,另一把椅子变成灰色。但事实是,复制和粘贴相同的代码一遍又一遍都很累,以实现它。我一直在考虑使用循环,但我无法弄清楚如何。反正有没有制作一个可循环的短代码或任何不需要一遍又一遍地复制和粘贴相同内容的东西?每个座位都已重命名为(Seat1,Seat2,Seat3,..)让我觉得可以使用循环吗?

1 个答案:

答案 0 :(得分:1)

为所有座位创建一个处理程序,并在显示表单时将处理程序挂钩到每个席位。我用三个座位测试了这个。

Const numofSeats As Integer = 3 'change to reflect number of seats
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    For x As Integer = 1 To numofSeats
        Dim lbl As Label = DirectCast(Me.Controls("Seat" & x.ToString), Label)
        lbl.BackColor = Color.Green
        AddHandler lbl.Click, AddressOf Seat_Click
    Next
End Sub

Private Sub Seat_Click(sender As Object, e As EventArgs)
    Dim lbl As Label = DirectCast(sender, Label)
    lbl.BackColor = Color.Brown
    '
    'Other? chair to gray?
    '
End Sub