I have a connect four game on a 10x10 grid where each slot is a PictureBox. Clicking one of the boxes will register the move and save it to a 10x10 two dimensional array. Then the PictureBox is changed to a red or blue color depending on who's turn it is.
When the user press one of the boxes it will run a method, this method has two integers as in-data called "row" and "col". Pressing a picture box will run this method with it's row and col number set as in-data. In this method there are 100 "if" statements that looks something like this:
if (row == 1 && col == 3)
{
pictureBox13.BackColor = Color.FromArgb(255, 58, 168, 241);
}
if (row == 1 && col == 4)
{
pictureBox14.BackColor = Color.FromArgb(255, 58, 168, 241);
}
if (row == 1 && col == 5)
{
pictureBox15.BackColor = Color.FromArgb(255, 58, 168, 241);
}
etc...
So, my question is if I really have to do it this way? I was wondering if there's a way for me to get the pictureBox using a string with the same name. Maybe something like this:
string name = "pictureBox" + row.ToString() + col.ToString(); // String is now "pictureBox13"
var pb = GetControllerByString(name);
pb.BackColor = Color.FromArgb(255, 58, 168, 241);
Obviously the code above won't work, but I used it as an example.
question from:
https://stackoverflow.com/questions/65887236/access-and-change-picturebox-controller-using-string 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…