I am trying to make a tic-tac-toe program, and want to know how I figure out if any of the buttons was clicked and which button it was. I am currently repeating the code inside every button:
private void button1_Click(object sender, EventArgs e)
{
button1.Visible = false;
label1.Text = "X";
Application.DoEvents();
}
private void button2_Click(object sender, EventArgs e)
{
button2.Visible = false;
label2.Text = "X";
Application.DoEvents();
}
private void button3_Click(object sender, EventArgs e)
{
button3.Visible = false;
label3.Text = "X"
Application.DoEvents();
}
Is there a more elegant way to do this?
There’s two ways to accomplish what you’re after (assuming WinForms)..
First, you could wire up all buttons to point to the same event handler.. and check its name:
Secondly, you could just put the logic into it’s own function and call that function for each individual event handler:
I would personally go with option 2 so that everything is clear.
It’s a trivial exercise though, considering you’ll only ever have a maximum of 9 buttons in a tic-tac-toe game.