Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add PictureBox to form at runtime

I'm making a C# program that will generate a PictureBox:

private void Form1_Load(object sender, EventArgs e)
{
    PictureBox picture = new PictureBox
    {
        Name = "pictureBox",
        Size = new Size(16, 16),
        Location = new Point(100, 100),
        Image = Image.FromFile("hello.jpg"),
    };
}

However, the control doesn't show up on my form. Why not?

like image 218
Octopus Avatar asked Dec 15 '22 12:12

Octopus


2 Answers

you can try this.. you need use this.Controls.Add(picture);

private void Form1_Load(object sender, EventArgs e)
    {
        var picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(16, 16),
            Location = new Point(100, 100),
            Image = Image.FromFile("hello.jpg"),

        };
        this.Controls.Add(picture);
    }

and if you want to remove from form at runtime.

 //remove from form
 this.Controls.Remove(picture);
  //release memory by disposing
 picture.Dispose();

;

like image 185
sm.abdullah Avatar answered Dec 28 '22 08:12

sm.abdullah


A control, such as a PictureBox, is just a class. There's nothing special about it, so a new PictureBox won't magically appear on your form.

All you need to do after instantiating and initializing a control is add the control to the container's Controls collection:

this.Controls.Add(picture);
like image 31
CodeCaster Avatar answered Dec 28 '22 07:12

CodeCaster