Rositsa Ruseva

Rositsa Ruseva

  • 1.5k
  • 218
  • 34.2k

Tic Tac Toe game - how to remove a button

Jan 15 2022 8:13 PM

I am currently making a Tic Tac Toe game with Windows Forms. I have a list of buttons that is storing all nine buttons (which are the game field). I have an AI as well - the first part of the game will be played by a player and a machine. I want to remove the selected button from the buttons list after the player selected it. However, I get this error on that line buttons.Remove(button) : System.NullReferenceException: 'Object reference not set to an instance of an object.'

Any idea how to fix it?

private void playerChose(object sender, EventArgs e)
{
    var button = (Button)sender;

    currentSymbol = Symbols.X;
    button.Text = currentSymbol.ToString();
    button.Enabled = false;
    button.BackColor = Color.FromArgb(224, 159, 62);
    buttons.Remove(button);
    CheckIfPlayerWon();
    MachineMove.Start();
}

 


Answers (1)