SaveFileDialog Issue in Visual Basic: Application Quits After First Use

Gaurav Gupta 0 Reputation points
2025-05-05T11:54:50.7666667+00:00

In a Visual Basic project, the 'SaveFileDialog' is correctly displayed the first time, but subsequent attempts to display it cause the application to quit unexpectedly. Here is the relevant code snippet:

Private Sub cmdPDF_Click(sender As Object, e As EventArgs) Handles cmdPDF.Click

    Debug.WriteLine("cmdPDF_Click: Entered") ' Add this line

    ' Show the SaveFileDialog to get the user's desired save location and filename.

    Dim savFileDialog As SaveFileDialog '= Nothing

    Try
        Debug.WriteLine("cmdPDF_Click: Before Try") ' Add this line
        savFileDialog = New SaveFileDialog()
        savFileDialog.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*"
        savFileDialog.Title = "Export Report to PDF"
        savFileDialog.FileName = "Export2PDF.pdf" 'Default File Name
        Debug.WriteLine("cmdPDF_Click: SaveFileDialog Initialized") ' Add this line
        
        ' Show the dialog and get the result.  Do this *once*.
        Dim dilogResult As DialogResult = savFileDialog.ShowDialog()
        Debug.WriteLine("cmdPDF_Click: ShowDialog returned: " & DialogResult.ToString()) ' Add this line

        'If the user clicks the save button on the dialog.
        If dilogResult = DialogResult.OK Then
            ' Get the file path from the SaveFileDialog.
            Dim filePath As String = savFileDialog.FileName
            Debug.WriteLine("cmdPDF_Click: filePath: " & filePath) ' Add this line
            Debug.WriteLine("cmdPDF_Click: Calling export2PDF") ' Add this line
            
            ' Call the ExportDataGridViewToPdf function to perform the actual export.
            export2PDF(dgView, filePath)
            Debug.WriteLine("cmdPDF_Click: export2PDF returned") ' Add this line

        Else
            Debug.WriteLine("cmdPDF_Click: DialogResult.Cancel/Other") ' Add this line
            MessageBox.Show("Process Cancelled by the user", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If

    Catch ex As Exception
        MessageBox.Show("Error showing/handling SaveFileDialog: " & ex.Message, "Dialog Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Debug.WriteLine("cmdPDF_Click: Exception: " & ex.Message) ' Add this line

    Finally
        If savFileDialog IsNot Nothing Then
            savFileDialog.Dispose()
        End If
    End Try
End Sub

What could be causing the application to quit after the first invocation of the SaveFileDialog? Any suggestions for debugging or fixing this issue?

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,845 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.