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.

Leave a Reply

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