Question

My partner and I are trying to figure out how to disable a button one at a time. We're making a program in Visual Studio Express 2012 that will disable a button once it is typed in a textbox. For example, we have five letters placed seperately on five different buttons If we were to put the letter "D" on the textbox, the button that contains that specific letter will be disabled. We're using the code

    If e.KeyCode = Keys.D Then
        Button1.Enabled = False
    End If

Now that works, BUT if there were two or more buttons that has the same letters, all of them disables because then the code will be :

    If e.KeyCode = Keys.D Then
        Button1.Enabled = False
    End If 

    If e.KeyCode = Keys.D Then
        Button2.Enabled = False
    End If

My problem would be in what way could I distinguish those buttons that has the same letter from one another so that when I type the letter on a textbox, only one button disables and when I type it in again, another button containing the same letter disables. Thanks!

Was it helpful?

Solution

Assuming all of the buttons are not in child panels:

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

OTHER TIPS

This will recursively iterate all controls on the form looking for buttons and disable them based on the characters and number of characters entered into the textbox:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top