JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Creating Open File Dialogs

Open File dialogs let you get the name and the path of files the user wants to open. You create these dialogs with the OpenFileDialog class, and you can see an example in the OpenFileDialog example on the CD-ROM.

This example lets the user open an image in a picture box. To configure the Open File dialog, I add an OpenFileDialog control to the project. To specify that I want the user to be able to open JPEG or GIF files, I use the Filter property of this control, which sets the possible file types this dialog can open. In this case, I'll set that property to this string at design time: "JPEG files (*.jpg)|*.jpg|GIF files (*.gif)|*.gif|All files (*.*)|*.*". This gives the user three prompts, "JPEG files (*.jpg)", "GIF files (*.gif)", and "All files (*.*)" in the "Files of type" box in the dialog box, and informs the program what file extensions to use by separating information with upright bars (|).

If the user did not click the Cancel button, I can determine which file they want to open from the FileName property, and load the corresponding image into the picture box in this example this way:

Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
    If OpenFileDialog1.ShowDialog() <> DialogResult.Cancel Then
        PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
    End If
End Sub

If you've set the dialog box's Multiselect property to True, the user can select multiple files—and you can recover their file names from the FileNames property, which returns an array of strings. Want to see an example? Take a look at "Adding Images to Image Lists in Code" in Chapter 10.

Another useful property to know about is the InitialDirectory property, which lets you set the directory that the Open File dialog box first shows; here's an example:

openFileDialog1.InitialDirectory = "c:\datafiles"

And here's another good one—if you set the dialog's ShowHelp property to True, it'll display a Help button. If that button is clicked, a HelpRequest event occurs, and you can display a help window when it does.


Don't forget that you can set the dialog box's title with the Title property in case you don't want it just to say "Open".

You can see the File Open dialog created in the OpenFileDialog example from the CD-ROM, which is shown in Figure 9.3.

Related solution:

Found on page:

Adding Images to Image Lists in Code


Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor