Question OpenFileDialog - how to do nothing if user click Cancel button?

villy

Member
Joined
Feb 11, 2009
Messages
10
Programming Experience
Beginner
Dear all,
I have a coding to let user select 2 files to import:
-------------------------------------------------------------------
Private Sub btn_Browse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBrowse1.Click
On Error Resume Next
OpenFileDialog1.Filter = "Lis files|*.lis"
OpenFileDialog1.FilterIndex = 1
OpenFileDialog1.ShowDialog()

txtFile1.Text = OpenFileDialog1.FileName
If txtFile1.Text.Equals("OpenFileDialog1") Then
txtFile1.Text = ""
End If
End Sub


Private Sub cmdBrowse2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBrowse2.Click

On Error Resume Next
OpenFileDialog1.Filter = "Lis files|*.lis"
OpenFileDialog1.FilterIndex = 1
OpenFileDialog1.ShowDialog()
txtFile2.Text = OpenFileDialog1.FileName
If txtFile2.Text.Equals("OpenFileDialog1") Then
txtFile2.Text = ""
End If

End Sub
-------------------------------------------------------------------
But if user click cancel button at Browse2 button, the system will paste the value from Browse 1 to Browse 2 text box.
How to do nothing if user click cancel button at OpenFileDialog?
Thanks. :confused:
 
Check the return value of the ShowDialog function method.
 
VB.NET:
        Dim dlgResult As DialogResult

        'Show dialog
        dlgResult = dlgOpen.ShowDialog

        'Exit if OK not clicked
        If dlgResult <> DialogResult.OK Then Exit Sub
 
VB.NET:
        Dim dlgResult As DialogResult

        'Show dialog
        dlgResult = dlgOpen.ShowDialog

        'Exit if OK not clicked
        If dlgResult <> DialogResult.OK Then Exit Sub
Personally, I aim to type as little as possible:
VB.NET:
If dlgOpen.ShowDialog(Me) <> DialogResult.Cancel
  'Not canceled
End If
 
You can also handle the FileOk event of the dialog instead of checking the return value.
 
Hi all,
Problem solved:

If OpenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
....
End If

Thanks all!! :)
 
Back
Top