How to create a picturebox dynamically in C #?

2

Well what I want to do is the generation of several boxes of images in my application of C #, in a few words a history of the images uploaded to my application. I currently have the following code:

Image Generation Code (Does not work).

    var directorio = new System.IO.DirectoryInfo(@"..\..\Imagenes\Imagenes_Modal\Usuario\Enero");
    PictureBox[] pics = new PictureBox[1000];
    for (int i=0;i<directorio.GetFiles().Length;i++) {
        pics[i] = new PictureBox();
        pics[i].Location = new Point(50,50);
        pics[i].Name = "pic" + i;
        pics[i].Size = new Size(300, 75);
        pics[i].ImageLocation = @"..\..\Imagenes\Imagenes_Modal\Usuario\Enero\Enero0.jpg";
    }

The above code in theory should create the images, in this case 3 images in your picturebox, I know that it would be emplamaria because they would be the same size and in the same location, that I intend to modify it, but at the moment it does not generate me not a single image, the winforms where they should be generated comes out in gray with nothing and those instructions are in the winform's constructor.

    
asked by David 05.04.2017 в 19:14
source

1 answer

5

Remember that you must add the instance of PictureBox to the collection of form :

var directorio = new System.IO.DirectoryInfo(@"..\..\Imagenes\Imagenes_Modal\Usuario\Enero");

foreach (var file in directorio.GetFiles()) 
{
    PictureBox pic = new PictureBox();
    pic.Location = new Point(50,50);
    pic.Name = "pic" + i;
    pic.Size = new Size(300, 75);
    pic.ImageLocation = file;

    this.Controls.Add(pic);
}

In the last line the this will be the same form where the control is added, if you want to do it against a Panel or another control you can also.

In addition you do not need a array of PictureBox , you can go creating them and adding them to form .

    
answered by 05.04.2017 / 19:21
source