我和我的伙伴正试图弄清楚如何一次禁用一个按钮。我们在Visual Studio Express 2012中创建了一个程序,它将在文本框中键入后禁用按钮。例如,我们将五个字母单独放在五个不同的按钮上如果我们在文本框中放置字母“D”,则将禁用包含该特定字母的按钮。我们正在使用代码
If e.KeyCode = Keys.D Then
Button1.Enabled = False
End If
现在可行,但是如果有两个或更多按钮具有相同的字母,则所有按钮都会禁用,因为代码将是:
If e.KeyCode = Keys.D Then
Button1.Enabled = False
End If
If e.KeyCode = Keys.D Then
Button2.Enabled = False
End If
我的问题是我能以何种方式区分那些具有相同字母的按钮,以便当我在文本框中键入字母时,只有一个按钮禁用,当我再次输入时,另一个按钮包含相同的字母禁用。谢谢!
答案 0 :(得分:1)
假设所有按钮都不在子面板中:
If e.KeyCode = Keys.D Then
For Each b As Button In Me.Controls.OfType(Of Button)()
If b.Text.Contains("D") AndAlso b.Enabled Then
b.Enabled = False
Exit For
End If
Next
End If
答案 1 :(得分:0)
这将递归迭代表单上的所有控件,查找按钮并根据输入到文本框中的字符和字符数禁用它们:
Private Sub textBox1_TextChanged(sender As Object, e As System.EventArgs)
Dim text As String = TryCast(sender, TextBox).Text.ToLower()
For Each b As Button In GetAllButtons(Me)
b.Enabled = True
Next
For Each c As Char In text
Dim count As Integer = text.Count(Function(cc) cc = c)
For i As Integer = 0 To count - 1
For Each b As Button In GetAllButtons(Me).Where(Function(x) x.Text.ToLower().Contains(c.ToString())).Take(count).ToList()
b.Enabled = False
Next
Next
Next
End Sub
Private Function GetAllButtons(control As Control) As List(Of Button)
Dim allButtons As New List(Of Button)()
If control.HasChildren Then
For Each c As Control In control.Controls
allButtons.AddRange(GetAllButtons(c))
Next
ElseIf TypeOf control Is Button Then
allButtons.Add(TryCast(control, Button))
End If
Return allButtons
End Function