Home > Back-end >  How to create an array with pictureboxes in windowsForms (C#)
How to create an array with pictureboxes in windowsForms (C#)

Time:02-19

I am fairly new to C# and I can't figure out how to create an array with visible pictureboxes inside the cs file. In this example I want to create 200 pictureboxes 10x20 to create an grid for a tetris game. This is my code, I can't get any of the pictures to show but the code runs just fine.

        Image[] blockImage = {
        TetrisSlutprojekt.Properties.Resources.TileEmpty,
        TetrisSlutprojekt.Properties.Resources.TileCyan,
        TetrisSlutprojekt.Properties.Resources.TileBlue,
        TetrisSlutprojekt.Properties.Resources.TileRed,
        TetrisSlutprojekt.Properties.Resources.TileGreen,
        TetrisSlutprojekt.Properties.Resources.TileOrange,
        TetrisSlutprojekt.Properties.Resources.TilePurple,
        TetrisSlutprojekt.Properties.Resources.TileYellow
    };

    PictureBox[] blockBoxes = new PictureBox[200];

    private void CreateBoxes()
    {
        for (int i = 0; i < blockBoxes.Length; i  )
        {
            blockBoxes[i] = new System.Windows.Forms.PictureBox();
            blockBoxes[i].Name = "pbBox"   i;
            blockBoxes[i].Size = new Size(30, 30);
            blockBoxes[i].Visible = true;
        }
    }

    private void PlaceBoxes()
    {
        for (int y = 0; y < rows; y  )
        {
            for (int x = 0; x < columns; x  )
            {
                blockBoxes[y].Top = y * blockWidth;
                blockBoxes[x].Left = x * blockWidth;
            }
        }
    }

    private void FillBoxes()
    {
        for (int i = 0; i < blockBoxes.Length; i  )
        {
            blockBoxes[i].Image = blockImage[4];
        }
    }

CodePudding user response:

Add them to the Form:

private void CreateBoxes()
{
    for (int i = 0; i < blockBoxes.Length; i  )
    {
        blockBoxes[i] = new System.Windows.Forms.PictureBox();
        blockBoxes[i].Name = "pbBox"   i;
        blockBoxes[i].Size = new Size(30, 30);
        blockBoxes[i].Visible = true;
        this.Controls.Add(blockBoxes[i]);  // <--- HERE
    }
}
  • Related