我正在Vb.net制作一个TicTacToe计划,它基本上是一场“大”游戏的9场比赛。所以我有81个按钮我想要禁用能够确定胜利者。如何用最短的代码解决所有这些问题呢?
Private Sub CheckOverallWinner()
If humangame1 = 1 And humangame2 = 1 And humangame3 = 1 Then
MsgBox("Human Wins")
Button1.Enabled = False
Button2.Enabled = False
Button3.Enabled = False
Button4.Enabled = False
Button5.Enabled = False
Button6.Enabled = False
Button7.Enabled = False
Button8.Enabled = False
Button9.Enabled = False
End If
End Sub
所以不是一直写到Button_.Enabled = False而是通过81更短的方式吗?谢谢!
答案 0 :(得分:0)
Dim o As Object
For Each o In Me.Controls
If TypeOf o Is Button Then
o.Enabled = False
End If
Next
在VS2008中试过这个
答案 1 :(得分:0)
使用Controls.Find()的另一个选项。无论按钮包含在哪里,这都可以工作,即使它们位于多个容器中:
Private Sub Foo()
SetButtonsState(False)
End Sub
Private Sub SetButtonsState(ByVal state As Boolean)
Dim matches() As Control
For i As Integer = 1 To 81
matches = Me.Controls.Find("Button" & i, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is Button Then
Dim btn As Button = DirectCast(matches(0), Button)
btn.Enabled = state
End If
Next
End Sub