Reputation: 11
I'm trying to program a matching game. My idea is:
(1). When a certain pictureBox1
is clicked, it becomes invisible
(2). A MessageBox
shows up, prompting "Pick another box."
(3). Finally, I need to program an if/else
statement where if pictureBox13
is clicked it becomes invisible; else
, (if another pictureBox
is clicked) a MessageBox
prompts "Try again." And both picture boxes become invisible, but I don't know what I am doing wrong:
// Program From Below
private void pictureBox1_Click(object sender, EventArgs e)
{
MessageBox.Show("Now Pick Another Hidden Picture!");
pictureBox1.Visible = false;
if (pictureBox13_Click)
{
MessageBox.Show("Great!");
pictureBox13.Visible = false;
}
else
{
MessageBox.Show("Try Again!");
}
}
There is a red squiggly line under if (pictureBox13_Click)
Upvotes: 0
Views: 5206
Reputation: 13676
As other suggested, you can use same event handler for all your pictureBoxes and cast sender
to PictureBox
to see what PB was clicked :
List<string> selectedPictureBoxes;
public MyForm() // ctor
{
selectedPictureBoxes = new List<string>();
foreach(Control c in this.Controls)
if(c is PictureBox) c.Click += pictureBox_Click;
}
private void pictureBox_Click(object sender, EventArgs e)
{
PictureBox _clicked = sender as PictureBox;
if(!selectedPictureBoxes.Contains(_clicked.Name))
selectedPictureBoxes.Add(_clicked.Name);
else ....
}
Upvotes: 1
Reputation: 2793
You could create an int
for the selected boxes (in this example, box1 and box2) which are both set to 0 and then create an on click event which sets the int to the clicked box.
if(box1 != 0)
{
box2 = 'insert selected box number'
}
else
{
box1 = 'insert selected box number'
}
After two boxes have been selected, both integers
can be set to false, this allows for you to use a switch
instead of if
, which could shorten the code substantially if a separate if
statement is required for each pair of pictures.
Upvotes: 0
Reputation: 486
It would be better if every PictureBox had it's a state, that you would then manipulate using a Click_Event. Microsoft has a comprehensive tutorial for a matching game here: https://msdn.microsoft.com/en-us/library/dd553235.aspx
Upvotes: 2