Issues with adding color to dynamically created pictureboxes in c#

I'm trying to add some life and color to dynamically created pictureboxes in panel.

I write this code:

Panel panel_main = new Panel();
this.Controls.Add(panel_main);
panel_main.Size = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
panel_main.BackColor = Color.Black;

PictureBox[] logos = new PictureBox[6];

for (int i  = 0; i < 6; i++)
{
    this.Controls.Add(logos[i]);
    logos[i] = new PictureBox();
    logos[i].BackColor = Color.Yellow;
    logos[i].Location = new Point(i * 10, i * 10);
    logos[i].Size = new Size(i * 40, i * 10);
    logos[i].Visible = true;
}

pictureboxes are shown on screen, but nor size, nor color appears correctly!

Upvotes: 0

Views: 79

Answers (2)

ASh
ASh

Reputation: 35730

// this.Controls.Add(logos[i]); // logos[i] is null yet
logos[i] = new PictureBox();
logos[i].BackColor = Color.Yellow;
logos[i].BorderStyle = BorderStyle.FixedSingle;
// 1. add pictureBoxes into panel
// 2. add pictureBoxes after you created them, not before
panel_main.Controls.Add(logos[i]);

enter image description here

Upvotes: 0

nikolifish
nikolifish

Reputation: 512

You have a few issues here.

First, you're adding nothing on this line

this.Controls.Add(logos[i]);

move this line to the bottom of your loop.

Second, your first box has zero size, that may not actually be an issue, but just so you know.

Third is how you're adding the control.

this.Controls.Add(logos[i]);

This will put the picturebox on the Form. My intution suggests that you actually want to use

panel_main.Controls.Add(logos[i]);

to add it to the panel rather than the form. If you really do want to use the form, after you add the control call BringToFront method on the picturebox.

logos[i].BringToFront();

Upvotes: 2

Related Questions