Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create an array with pictureboxes in windowsForms (C#)

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 10×20 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];
        }
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);  // <--- HERE
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading