Search code examples
vb.netopenfiledialog

Why do I have to cancel OpenFileDialog twice for it to close


Here is the code:

  Private Sub btn_selectfile_Click(sender As Object, e As EventArgs) Handles btn_selectfile.Click
    OpenFileDialog1.FileName = ""
    OpenFileDialog1.Filter = "Text Files | *.txt"

    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        'some code here
    ElseIf OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.Cancel Then
        OpenFileDialog1.Dispose()
    End If

End Sub

It also happens if I reverse them and put the DialogResult.OK in the ElseIf when selecting a file.

How shall I proceed? Thanks for your help.


Solution

  • Call ShowDialog once, save the result, and then check it. Currently, you're calling ShowDialog twice, which shows the dialog to the user twice.

    Dim result As DialogResult = OpenFileDialog1.ShowDialog();
    
    If result = Windows.Forms.DialogResult.OK Then
        'some code here
    ElseIf result = Windows.Forms.DialogResult.Cancel Then
        OpenFileDialog1.Dispose()
    End If