Thursday, 13 March 2014

OpenFileDialog in C#

Hi Friends, 

This tutorial is a continuation of First C# Windows Form Application. So now you know how to create a Windows Form Application in c#. Here you will learn how to use OpenFileDialog. OpenFileDialog is a control that allows users to browse folders and select files.

Here is a tutorial for creating an Image Viewer with OpenFileDialog. 


1.Create a New Project -> Windows Form Application.
   Give the name as "OpenFileDlg"

2. Now design the form as given in the below screenshot. 
3. To add an OpenFileDialog, click on the control from the toolbox and drag it to the
    form. It will appear in its own area below your form when you try to place it on the 

4. Now click on the button -> Right mouse click -> select Properties (or click on the
    button and press F4) and change 

    Name - btnBrowse
    Text   - Browse    

5. Now open Form1.cs and update the code as given below.


using System;
using System.Windows.Forms;

namespace OpenFileDlg

    public partial class Form1 : Form
        public Form1()
            //To set the title for the Form
            this.Text = "Image Viewer";

        private void btnBrowse_Click(object sender, EventArgs e)

            openFileDialog1.FileName = String.Empty;
            //To filter image file formats from others
            openFileDialog1.Filter = "Image Files (*.jpg,*.png,*.bmp)|*.jpg;*.png;*.bmp|All Files (*.*)|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                //To display the selected filepath in the textbox
                 textBox1.Text= openFileDialog1.FileName;
                //To fit the image in the picturebox
                 pictureBox1.SizeMode  = PictureBoxSizeMode.StretchImage ;
                //To display the selected image in the picturebox
                 pictureBox1.ImageLocation = textBox1.Text;



See the Screenshot

6. On adding filter in OpenFileDialog, if you want to add another

    format, just do the following;

    openFileDialog1.Filter = "Image Files (*.jpg,*.png,*.bmp)|*.jpg;*.png;*.bmp|
   All Files(*.*)|*.*";

    Adding 'gif' format in the filter
    openFileDialog1.Filter = "ImageFiles(*.jpg,*.png,*.bmp,*.gif)|*.jpg;*.png;*.bmp;*.gif|
    All Files(*.*)|*.*";

   7. Rebuild your Project and Run. Now click on Browse, select an image and press OK,the
       image will be displayed on the picture box. See the output below;



Now you have learned to create a simple Image viewer in C# using Picture box and OpenFileDialog. Feel free to comment in case of any errors or doubts.

See Also

1 comment:


About Me

I am Tijo Tom, a Computer Engineer from India.Right from my schooling, I had a passion for Programming, PC Tricks, Virus Creation and Hacking.

I started this blog on Jan 1, 2014 to share my views and ideas with the world.

You can know more about me on