Change button color when pressed (multiple buttons)

Im doing a tictactoe game in vb.net and i would like to know how to change button color for example when setting X or O to a button, like when X is assigned turn the button blue and when O is assigned turn it green.

heres the code assign x or o

Private Sub AllButton_Click(sender As Object, ByVal e As EventArgs)
    If turn Mod 2 = 0 And sender.Content = "" Then
        sender.Content = "X"
    Else
        If sender.Content = "" Then
            sender.Content = "O"

        End If
    End If
    turn += 1
End Sub

Upvotes: 0

Views: 637

Answers (2)

Andrew Stephens
Andrew Stephens

Reputation: 10193

Instead of doing it in code-behind, why not use XAML? Something like this:-

  <Style x:Key="MyButtonStyle" TargetType="Button">
    <Setter Property="Background" Value="White" />
    <Style.Triggers>
      <Trigger Property="Content" Value="X">
        <Setter Property="Background" Value="Red" />
      </Trigger>
      <Trigger Property="Content" Value="O">
        <Setter Property="Background" Value="Blue" />
      </Trigger>
    </Style.Triggers>
  </Style>

Then assign it to your buttons:

<Button Style="{StaticResource MyButtonStyle}" />

The style sets a default background of white, and uses triggers to change the background colour based on the button content ("X" or "O").

Upvotes: 1

averyto8
averyto8

Reputation: 45

Wouldn't it just be button1.BackColor

UPDATE: notice the 2 lines of code added to each section of the if statement

Private Sub AllButton_Click(sender As Object, ByVal e As EventArgs)
    If turn Mod 2 = 0 And sender.Content = "" Then
        sender.Content = "X"
        Button1.BackColor = Color.Blue
        Button2.BackColor = DefaultBackColor

Else
    If sender.Content = "" Then
        sender.Content = "O"
        Button2.BackColor = Color.Green
        Button1.BackColor = DefaultBackColor

    End If
End If
turn += 1
End Sub

Upvotes: 0

Related Questions