Access to a specific instance of a Winform control

In this im writing program, I use a function to create multiple instances of a PictureBox. This is the code:

public void serverCard()
{
    //Definitions
    PictureBox cardBack = new PictureBox();

    //Specifics for card
    cardBack.Size = new Size(cardSizeX, cardSizeY);
    cardBack.BackColor = Color.White;
    cardBack.Left = startX;
    cardBack.Top = startY;

    serverArea.Controls.Add(cardBack);

    //differences in pos
    startX += cardBack.Width + 5;
    if (startX > this.Width - cardSizeX)
    {
      startY += cardBack.Height + 5;
      startX = 5;
    }
}

How do I access a specific instance of PictureBox. For example: I create 5 PictureBoxes called "cardBack" using this function. I want to reposition the second created Picture Box, how would I do it.

+4
source share
2 answers

1) You can either give everyone a PictureBoxdifferent name (maybe "cardBack" + ID_in_int)

int picBox_ID = 1;
public void serverCard()
{
    PictureBox cardBack = new PictureBox();
    cardBack.Name = "cardBack" + picBox_ID;
    picBox_ID++;

and pull them out Controlsby name:

PictureBox temp = serverArea.Controls.OfType<PictureBox>().FirstOrDefault(x=>x.Name == "cardBack2");

2), : List<PictureBox>,

List<PictureBox> picCollection = new List<PictureBox>();
public void serverCard()
{
    PictureBox cardBack = new PictureBox();
    picCollection.Add(cardBack);

, . , .

3) , PictureBox int ID. , , PictureBox. Controls .

+4

, PictureBox

public PictureBox CreatePictureBox ()
{
  // your code from question here
}

private Dictionary<string, PictureBox> pboxes = new Dictionary<string, PictureBox>();

, PictureBox, pboxes:

pboxes.Add("box1", CreatePictureBox());    

:

pboxes [ "box1" ]. + = 20;

+1

Source: https://habr.com/ru/post/1682670/


All Articles