I am trying to make a memory game. I have 16 different pictureboxes(pbx1, pbx2...).
And now I am trying to make them revert to questionmarks after a wrong guess. This is what I've so far done:
void questionMarker(int lastBoxCLicked)
{
if(lastBoxClicked == 1)
{
pbx1.Image = Image.FromFile("../Bilder/Frågetecken.png");
}
else if(lastBoxClicked == 2)
{
pbx2.Image = Image.FromFile("../Bilder/Frågetecken.png");
}
else if (lastBoxClicked == 3)
{
pbx3.Image = Image.FromFile("../Bilder/Frågetecken.png");
}
else if (lastBoxClicked == 5)
{
pbx4.Image = Image.FromFile("../Bilder/Frågetecken.png");
}
}
But this becomes quite tedious and horrendous to look at as I have 16 pbx'es. Is there any way to write it like this?:
void questionMarker(int lastBoxClicked)
{
pbx[lastBoxClicked].Image = Image.FromFile("../Bilder/Frågetecken.png");
}
If I put this code in it just says that there is nothing named pbx.
CodePudding user response:
Try this:
PictureBox[] PictureBoxArray = new PictureBox[3];
This creates an array of 3 picture boxes called PictureBoxArray.
You can loop through like an ordinary array or access certain picture boxes using PictureBoxArray[i]
CodePudding user response:
After your update, i think you have a click handler of the PictureBox
. If that's true you just need
void PictureBox_Click(object sender, EventArgs e)
{
((PictureBox)sender).Image = Image.FromFile("../Bilder/Frågetecken.png");
}
If that's not possible and you insist in using your approach:
void QuestionMarker(int lastBoxCLicked)
{
PictureBox[] allPb = parentControl.Controls.OfType<PictureBox>().ToArray();
PictureBox clicked = allPb.ElementAtOrDefault(lastBoxCLicked-1); // index is zero based
if(clicked != null)
{
clicked.Image = Image.FromFile("../Bilder/Frågetecken.png");
}
}
You need to add using System.Linq
.
CodePudding user response:
Just use the "recurse" option of Controls.Find()
. This will find the control "by name" no matter where or how deeply nested it is on the form:
Image questionMark = Image.FromFile("../Bilder/Frågetecken.png");
void questionMarker(int lastBoxCLicked)
{
PictureBox pb = this.Controls.Find("pbx" lastBoxCLicked, true).FirstOrDefault() as PictureBox;
if (pb != null)
{
pb.Image = questionMark;
}
}