Use a loop to load pictures in C#

[load pictures]

When the form loads, the following code loads pictures into the form’s PictureBoxes.

private void Form1_Load(object sender, EventArgs e)
    string dirname = Path.GetFullPath(
        Path.Combine(Application.StartupPath, @"..\..\"));

    // Make an array holding the PictureBoxes.
    PictureBox[] pics =
        { PictureBox1, PictureBox2, PictureBox3, PictureBox4 };

    // Load the pictures in a loop.
    for (int i = 0; i < pics.Length; i++)
        string filename = dirname + "pic" + i.ToString() + ".png";
        using (Bitmap bm = new Bitmap(filename))
            pics[i].Image = (Bitmap)bm.Clone();

The code builds the path to the image files. It then creates an array holding references to the form’s PictureBoxes. (If you use this array in more than once place, you can declare it at the class level so you don’t need to recreate it later.)

The program then loops through the file names pic0.png, pic1.png, and so forth. For each file name, the code composes the full file name including the directory path. It then loads the image file into a Bitmap. The Bitmap is created inside a using block so the program automatically calls its Dispose method.

Inside the block, the program clones the Bitmap and displays the result in a PictureBox. Cloning and disposing of the original Bitmap ensures that the image file isn’t locked by the program.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in graphics, image processing and tagged , , , , , , , , , . Bookmark the permalink.

2 Responses to Use a loop to load pictures in C#

  1. matt says:

    pls how do archive such task by creating a single picture box and then loop through all the picture in my database!!

    plsease i dont know if you really understand what im trying to archive

    like i have mutilple image in the database but want to loop through and show each in each picture and when new record is added to the database it will automitically show in the picture box along with the other !!

    • RodStephens says:

      Take a look at this post:

      Display database pictures in a ListView control in C#

      It should give you the basics of how to load pictures from a database. You can then loop through them.

      You may want to use a database field to select the images so you can get them in the proper order. For example, you could call that field ImageNumber or something.

      You may also want to pre-load the images and then loop through them in memory. That will be much faster.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.