Search code examples
vb.netformspathfolderbrowserdialog

Form closes when clicking OK in a FolderBrowserDialog - vb.net


I have a Main form and an Options form which starts when clicking on "Options" button in Main form. In the Options form, I have to select the work path. When clicking "OK" button in Options form to come back to the Main form, I want to check if the work path exists:

If My.Computer.FileSystem.DirectoryExists(TextBoxWorkPath.Text) Then
   Main.WorkPath = TextBoxWorkPath.Text
Else
   MessageBox.Show("Please, enter a valid work path.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
   ButtonChangePath_Click(sender, New System.EventArgs())
End If

The code behind ButtonChangePath_Click() (in Options form) is:

Private Sub ButtonChangePath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonChangePath.Click
        Dim fb = New FolderBrowserDialog
        fb.Description = "Select the destination folder for the output files:"
        If fb.ShowDialog() = DialogResult.OK Then
            TextBoxWorkPath.Text = fb.SelectedPath
        End If
End Sub

When I check if the work path exists, I open again the FolderBrowserDialog to select a correct path. But when I click "OK" the Options form closes and turn to Main form. If I click again in "Options" button, the work path is the same as before.


Solution

  • Finally, I fixed it. I had to place Windows.Forms.DialogResult.None in the If statement, in order to not to close the Options form.

    If My.Computer.FileSystem.DirectoryExists(TextBoxWorkPath.Text) Then
        Main.WorkPath = TextBoxWorkPath.Text
    Else
        MsgBox("Please, enter a valid work path.", MsgBoxStyle.Exclamation, "Attention!")
        Me.DialogResult = Windows.Forms.DialogResult.None
    End If
    

    So, when clicking on OK button, still stay in the Options form.