What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleUse the common dialog control to select a file
DescriptionThis example shows how to use the common dialog control to select a file in Visual Basic 6. It uses the dialog's ShowOpen method to let the user select a file.
Keywordscommon dialog, select file, pick file
CategoriesControls, Files and Directories
When the program loads, it initializes its common dialog control. It sets the dialog's title and sets its initial directory to the application's startup path.

It creates a filter that lets the user select text files or all files. The Filter property is a list alternating between the text shown to the user and the pattern that the files should match. The program selects the first filter.

Next the program sets flags to ensure that the user can only select files that actually exist. It hides the dialog's Read Only button, displays long file names, and uses an Explorer-style interface.

Finally, it sets the dialog's CancelError property to True. This makes the dialog raise an error if the user cancels instead of selecting a file.

Private Sub Form_Load()
    dlgOpenFile.DialogTitle = "Open File"
    dlgOpenFile.InitDir = App.Path
    dlgOpenFile.Filter = "Text Files (*.txt)|*.txt|All " & _
        "Files (*.*)|*.*"
    dlgOpenFile.FilterIndex = 1
    dlgOpenFile.Flags = _
        cdlOFNFileMustExist + _
        cdlOFNHideReadOnly + _
        cdlOFNLongNames + _
    dlgOpenFile.CancelError = True
End Sub
When the user clicks the Open button, the program calls the dialog's ShowOpen method. It does this within an error handler so it can catch any errors. It then checks the error to see if the user canceled, if there was an unexpected error, or if the user selected a file.

If the user selected a file, the program reads it and displays it in the txtFile TextBox.

Private Sub mnuFileOpen_Click()
Dim fnum As Integer

    On Error Resume Next
    If Err.Number = cdlCancel Then
        ' The user canceled.
        Exit Sub
    ElseIf Err.Number <> 0 Then
        ' Unknown error.
        MsgBox "Error " & Format$(Err.Number) & _
            " selecting file." & vbCrLf & _
        Exit Sub
    End If
    On Error GoTo 0

    ' Read the file.
    fnum = FreeFile
    Open dlgOpenFile.FileName For Input As #fnum
    txtFile.Text = Input$(LOF(fnum), fnum)
    Close #fnum
End Sub
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.