Displaying the Open Common Dialog Box

The Open common dialog box enables a user to browse through directories and select a file name. The Open dialog box has properties that enable you to change the appearance and behavior of the dialog box. For example, you can define filters for file names or require that the user select a file from a pre-defined list.

The Open dialog box uses the FileName, FileTitle, and InitDir properties to provide a default path and file name. You can set the caption for the dialog box with the DialogTitle property and set filters that display only certain files with the Filter and FilterIndex properties. The Flags property enables you to adjust other control dialog behaviors, such as validating paths or file names.

Use the ShowOpen method to show the dialog box after you set its properties. When the ShowOpen method returns, the application can read the properties to determine the choices a user made in the dialog box.

The following code example shows how to display an Open common dialog box and return the selected file name and path.

Public Function GetFileToOpen()
    Dim fileflags As FileOpenConstants
    Dim filefilter As String
    'Set the text in the dialog title bar
    CommonDialog1.DialogTitle = "Open"
    'Set the default file name and filter
    CommonDialog1.InitDir = "\"
    CommonDialog1.FileName = ""
    filefilter = "Visual Basic Files (*.vb)|*.vb|All Files (*.*)|*.*"
    CommonDialog1.Filter = filefilter
    CommonDialog1.FilterIndex = 0
    'Verify that the file exists
    fileflags = cdlOFNFileMustExist
    CommonDialog1.Flags = fileflags
    'Show the Open common dialog box
    CommonDialog1.ShowOpen
    'Return the path and file name selected or
    'Return an empty string if the user cancels the dialog
    GetFileToOpen = CommonDialog1.FileName
End Function