2014-01-29 24 views
0

我的合作伙伴和我正試圖弄清楚如何一次禁用一個按鈕。我們正在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

因此,如果您有兩個帶文本「D」的按鈕,您希望在鍵入文本框時連續禁用更多次輸入字母的按鈕?所以如果你輸入「D」,第一個禁用,那麼如果你輸入另一個「D」,使文本框「DD」,第二個禁用? – Brandon

回答

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 
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 
相關問題