[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use a loop to load pictures in C#

[Use a loop to load pictures in C#]

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 the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.