Visual C#

The Open Dialog Box

Besides saving files, another common operation performed by users consists of opening files. This refers to existing files since a file must primarily…

1 min read159 words1 code sample

Description#

Beyond simply saving data, users often need to retrieve and open existing files. Since a file can only be opened if it already exists, Microsoft Windows provides a standardized Open File dialog box to handle this task:

Open File Dialog Box Creation#

To provide file opening support, the .NET Framework provides the OpenFileDialog class which is derived from the FileDialog class that in fact provides most of its functionality. The easiest way to use it is to click the OpenFileDialog button from the Toolbox and click the form. You can click anywhere on the form because the OpenFileDialog object would not be seen at run time. After placing it on the form, you can use the Properties window to configure it.

To generate an Open dialog box through code, you can define an OpenFileDialog variable and initialize it by calling its default constructor with the new operator. Consider this example:

C#
using System;
using System.Windows.Forms;

public class Exercise : Form
{
    private OpenFileDialog  ofd;

    public Exercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        ofd = new OpenFileDialog();
    }
}

public class Program
{
    public static int Main()
    {
        Application.Run(new Exercise());

        return 0;
    }
}

Index Page Copyright © 2008-2009 C# Key Next