Search code examples
c#winforms

Is there a way to reference a picturebox just created and added during runtime?


Im using Visual Studio Community with the Windows Forms template, and was wondering if there is a way to reference a newly created pcb when created during runtime like shown in code:

for (int i = 0; i <= mapSize - 1 && !foundPos; i++)
{
    for (int j = 0; j <= mapSize - 1 && !foundPos; j++)
    {
        var pcb = new PictureBox();
        pcb.Name = "pcb" + i + "" + j;
        pcb.Margin = new Padding(0);
        pcb.Size = new Size(slotSize, slotSize);
        pcb.Location = new Point(0 + i * slotSize, 0 + j * slotSize);
        if (currMap[i, j] == 5)
            pcb.BackColor = Color.Yellow;
        if (currMap[i, j] == 0)
            pcb.BackColor = Color.White;
        if (currMap[i, j] == 1)
            pcb.BackColor = Color.Gray;
        this.Controls.Add(pcb);

    }
}

this.pcb00.BackColor = Color.Yellow; // A way to reference the pictureboxes just made?

i gave the picturebox a name when i created it and tried using the name of the picturebox like normal.


Solution

  • You'll need to either keep a reference to the variable created or perform operations on the Controls container it's in to find it later. In my own application I have a custom control, and I keep a dictionary<string, MyCustomControl> that I add the generated controls to for easier access.

    See the answers here for information on using either this.Controls.Find() or this.Controls[name] to find the control if needed.