Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
731 views
in Technique[技术] by (71.8m points)

variables - Access and change pictureBox controller using string

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...