0

I'm trying to make a simple game using a 10x10 grid of empty pictureboxes, and I've run into a very specific problem.

The idea is that the application makes a calculation based on player input and changes the backcolor of specific pictureboxes in the grid. Though how exactly that works isn't really important to this question.

The pictureboxes are named pictureBox1, pictureBox2, etc. (All the way up to 100).

I know that I can change the backcolor with this line of code:

pictureBox1.BackColor = Color.FromArgb(int, int, int);

Now let's say the application returns the variable int resultValue = 25, which means that I want pictureBox25 to change its Backcolor. Now, if I could just write the code like this:

string pbName = "pictureBox" + resultValue.toString();

pbName.BackColor = Color.FromArgb(int, int, int);

...then there wouldn't be a problem. But Visual Studio doesn't seem to accept a string varable in place of a name.

Is there any type of variable it would accept, or is there another way to accomplish what I need without resorting to a giant if-statement.

leppie
  • 115,091
  • 17
  • 196
  • 297
JMS
  • 3
  • 1
  • 3
  • 2
    See http://stackoverflow.com/questions/1536739/get-a-windows-forms-control-by-name-in-c-sharp to find a control by name. – WraithNath Nov 25 '15 at 10:49
  • 1
    Additionally, this is probably the least efficient way to make a game like this. You should really draw the grid yourself, would make things a lot easier and faster than PictureBox controls... – Luke Joshua Park Nov 25 '15 at 10:51
  • If sticking to the basic design, you ought to to put references to the pixtureboxes in a 2d array upon setup. Using a DataGridView would be even simpler. – TaW Nov 25 '15 at 18:10

1 Answers1

0
Control []controls=this.Controls.Find("pictureBox" + resultValue.ToString(), true);
        if (controls != null && controls.Length > 0)
        {
            foreach (Control control in controls)
            {
                if (control.GetType() == typeof(PictureBox))
                {
                    PictureBox pictureBox = control as PictureBox;
                    pictureBox.BackColor = Color.FromArgb(r, g, b);
                }
            }
        }
Ehsan.Saradar
  • 664
  • 6
  • 10