【问题标题】:Disabling buttons one at a time一次禁用一个按钮
【发布时间】:2014-01-29 17:48:22
【问题描述】:

我和我的搭档正试图弄清楚如何一次禁用一个按钮。我们正在 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

我的问题是如何区分具有相同字母的按钮,这样当我在文本框中键入字母时,只有一个按钮会被禁用,当我再次键入时,另一个按钮包含相同的字母禁用。谢谢!

【问题讨论】:

  • 那么,如果你有两个按钮,都带有文本“D”,你希望当你在文本框中输入时,你输入的字母越多,按钮就连续禁用?所以如果你输入“D”,第一个禁用,然后如果你输入另一个“D”,使文本框变成“DD”,第二个禁用?

标签: vb.net button keycode


【解决方案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

【讨论】:

    【解决方案2】:

    这将递归地迭代表单上的所有控件以查找按钮并根据输入到文本框中的字符和字符数禁用它们:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 2011-08-01
      • 2020-09-18
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多