The second step is to select a folder with pictures.
When the user selects a folder all of the picture files in the folder will be displayed in a combo box.
When the user selects one of the pictures from the combo box, that picture will be displayed in the picture box.
Continue with the PictureViewer application.
Add the following controls:
A combo Box , cboPictures.
A FolderBrowserDialog , FolderBrowserDialog1
Double click on the mnuSelectFolder and write the code shown below: Don't overlook adding using System.IO!
// Programmer: Janet Joy
// PIcture Viewer app: Select a picture file and display it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace picture_viewer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void mnuOpen_Click(object sender, EventArgs e)
{
// Set the filter so that only pictures can be selected.
openFileDialog1.Filter = "All Pictures|*.bmp;*.gif;*.png;*.jpg|JPG|*.jpg|Bitmaps|*.bmp|GIFS|*.gif|PNG|*.png";
// Get rid of any previous filename
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
// If the user clicks CANCEL the filename is blank
if (openFileDialog1.FileName != "")
{
// Load the selected picture into the picture box
picShow.Load(openFileDialog1.FileName);
// Display the name of the file
Text = openFileDialog1.FileName;
}
}
private void mnuExit_Click(object sender, EventArgs e)
{
// End the program by closing the form.
this.Close();
}
private void mnuSelectFolder_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
if(folderBrowserDialog1.SelectedPath!="")
{
// Remove any files that were selected previously.
cboPictures.Items.Clear();
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath,"*", SearchOption.AllDirectories);
// Add each file to the combo box.
foreach (String s in files)
{
// Convert s to upper case for ease of comparing
string upper = s.ToUpper();
// Only add to combo box if a picture.
if (upper.Contains(".JPG") || upper.Contains(".PNG") || upper.Contains(".BMP") || upper.Contains(".GIF"))
{
cboPictures.Items.Add(s);
}
}
// If no pictures were found in the selected folder don't display the combo box.
if (cboPictures.Items.Count > 0)
{
// Select the first item in the combo box.
cboPictures.SelectedIndex = 0;
cboPictures.Visible = true;
}
else {
cboPictures.Visible = false;
}
}
}
}
}
Test your program and try selecting a folder that contains pictures. You should see the names of the files, but the pictures don't display.
Save all before moving on to the next step.
Complete code so far