PictureBox on panel in c# window application

How to add multiple images picture box on panel using c# through coding just like this pic you can see pic and tell me
Capture01.PNG
Sharrif HussainDeveloperAsked:
Who is Participating?
 
Dustin SaundersDirector of OperationsCommented:
So, to give a more detailed explanation in code, I have a folder called C:\test\images and pictures called cat1.jpg - cat5.jpg.

In code:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadImages();
        }

        private string filePath = @"C:\test\images\";

        private void LoadImages()
        {
            FlowLayoutPanel flp = new FlowLayoutPanel
            {
                Size = new Size(this.Width - 20, this.Height - 20),
                Location = new Point(10, 10)
            };

            for (int i = 1; i <= 5; i++)
            {
                PictureBox pb = new PictureBox
                {
                    Image = Image.FromFile(filePath + "cat" + i.ToString() + ".jpg"),
                    Size = new Size(75, 75),
                    SizeMode = PictureBoxSizeMode.StretchImage
                };
                              

                flp.Controls.Add(pb);
            }
            
            this.Controls.Add(flp);
        }
    }

Open in new window


This will load each image into my FlowLayoutPanel and automatically space them.

cats.png
0
 
Dustin SaundersDirector of OperationsCommented:
You've got a couple of options, ways to do this.  You can load the controls in and space them yourself if you want to have absolute control over where they go:

Panel panel;

        List<PictureBox> pictures;

        public void load()
        {
            int loaded = 0;
            int padding = 4;

            foreach (PictureBox p in pictures)
            {
                p.Location = new System.Drawing.Point(padding + (loaded * (p.Width + padding)), padding);
                panel.Controls.Add(p);
            }
        }

Open in new window


Or, what would be simpler, is to replace your panel with a FlowLayoutPanel and then just add the controls to that.  You can adjust the configuration in the VS IDE.

            FlowLayoutPanel flp = new FlowLayoutPanel();
            foreach (PictureBox p in pictures)
            {
                flp.Controls.Add(p);
            }

Open in new window


Much simpler.
0
 
Dustin SaundersDirector of OperationsCommented:
Answers and examples on how to accomplish the request.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.