How to import different pictures in many pictureboxe?

lynxAi

Member
Joined
Dec 7, 2019
Messages
15
Location
SiChuan China
Programming Experience
Beginner
See title, I have 52 Picturebox controls, How to batch add pictures to these 52 Pictureboxes?
 
Programmatically create the picture boxes instead of laying them out with the WinForms designer. If possible put them into a TableLayoutPanel or a FlowLayoutPanel so that you don't have to compute the individual positions. Then all you need is a for loop that iterates 52 times. In the loop create the picture box, load the image appropriate for that picture box, and then stuff the picture box into a layout panel.
 
poke:
            int Num = 0;
            PictureBox[] pb;
            Num = 52;
            pb = new PictureBox[Num];
            for (int i = 1; i < Num; i++)
            {
                pb[i] = new System.Windows.Forms.PictureBox();
                pb[i].BorderStyle = BorderStyle.FixedSingle;
                pb[i].Location = new Point(50 + i * 110, 100);
                pb[i].SizeMode = PictureBoxSizeMode.Zoom;
                pb[i].Image = Image.FromFile(@"D:\pic\" + i + ".png");
                FlowPanel1.Controls.Add(pb[i]);
            }
 
but
desktop.png
 
You have to put all that highlighted code in a method. You can't just throw arbitrary code anywhere you like in a class. If it's not a declaration, it has to be inside a method, so it gets executed when that method is called. If you want to execute code when a form is loaded then, not surprisingly, you handle the Load event and put your code in the event handler.

Also, most of that code is pointless. Why write code to create all those controls when you can just add them in the designer? You can then simply set the Image property of the existing controls in your code.

BTW, the whole point of using a FlowLayoutPanel is that it will handle the layout for you. You're not supposed to be setting the Location property, as you were told previously?
 
Back
Top Bottom