In this article I will explain with an example, how to display Image from Folder (Directory) in PictureBox control in Windows Forms (WinForms) Application using C# and VB.Net.
Form Design
The Form consists of following controls:
Button – For selecting the file.
The Button has been assigned with a Click event handler.
Label – For labelling and displaying name of the selected file.
PictureBox – For displaying the selected image.
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Drawing;
VB.Net
Imports System.IO
Imports System.Drawing
Displaying Images from Folder (Directory) in PictureBox using C# and VB.Net
When the Choose File Button is clicked, the OpenFileDialog class object is created.
After that the Dialog Box is opened using ShowDialog method, and if the DialogResult is OK then the name of the image file is set into a Label control using the GetFileName method of the Path class.
Finally, the selected Image file is displayed in PictureBox control using the FromFile method of the Image class.
C#
private void OnChoose(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
lblFileName.Text = Path.GetFileName(openFileDialog1.FileName);
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
}
}
}
VB.Net
Private Sub OnChoose(sender As Object, e As EventArgs) Handles btnChoose.Click
Using openFileDialog1 As OpenFileDialog = New OpenFileDialog()
If openFileDialog1.ShowDialog() = DialogResult.OK Then
lblFileName.Text = Path.GetFileName(openFileDialog1.FileName)
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName)
End If
End Using
End Sub
Screenshot
Downloads