0

I am fairly new to C# and I can't figure out how to create an array with visible picture boxes inside the cs file. In this example I want to create 200 picture boxes 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];
    }    
}
2
  • 1
    Controls must be added to the Form's controls collection. You dont need the forms designer tag - manually adding controls avoids the designers Commented Feb 19, 2022 at 0:34
  • Like this? Controls.Add(pbBox1); Commented Feb 19, 2022 at 0:42

1 Answer 1

1

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
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This solved my issue. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.