Introduction
While working on the development of applications, some times we can save a lot of time if we can find reusable code on the internet. I was searching for a tool to display images in a form to allow a user to select one of them. After searching for a while, I decided to develop this and to post it here on CodeProject. It's a simple user form and is easy to understand. You can include it in your application by adding the three source files into your project.
Displaying the Form
There are two ways to load images. One is by filling the String
array named imgList
that contains the list of files to be displayed:
FormSelectImage form = new FormSelectImage();
form.imgSize = new Size( 200, 200 );
form.imgList = myListOfFiles;
if( form.ShowDialog() == DialogResult.OK )
{
String selectedImage = form.selectedImg;
}
The other method is by calling the function scanDirectory
. This function scans the directory with the given search pattern and stores the found files in imgList
.
FormSelectImage form = new FormSelectImage();
form.imgSize = new Size( 200, 200 );
form.scanDirectory( "C:\\myFiles", "*.jpg", System.IO.SearchOption.AllDirectories );
if( form.ShowDialog() == DialogResult.OK ) {
String selectedImage = form.selectedImg;
}
How it Works
The form contains an empty scrollable panel that will be filled when onLoad
is called. It generates a PictureBox
for each image, then adds the image into the panel.
foreach( String img in imgList )
{
PictureBox pb = new PictureBox();
pb.Size = imgSize;
pb.SizeMode = PictureBoxSizeMode.Zoom;
pb.Image = Image.FromFile( img );
pb.BackColor = Color.White;
pb.Click += new EventHandler( pb_Click );
pb.Tag = img;
panel1.Controls.Add( pb );
}
Final Words
I like to develop, and have found a lot of help here on CodeProject; I hope that this little article will help someone else.