conquistador conquistador - 1 month ago 16
Vb.net Question

Use only one OpenFileDialog for multiple and different situations

I have a program that uses multiple

OpenFileDialog
but I want to use one. I have written a code that does that but is there a simpler way to do that?

Public Class Form1
Private _intFlag As Integer = 0

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
_intFlag = 1
OpenFileDialog1.ShowDialog()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
_intFlag = 2
OpenFileDialog1.ShowDialog()
End Sub

Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
If _intFlag = 1 Then
TextBox1.Text = OpenFileDialog1.FileName
ElseIf _intFlag = 2 Then
TextBox2.Text = OpenFileDialog1.FileName
End If
End Sub
End Class

Answer

I would suggest not handling the FileOk event.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
        TextBox1.Text = OpenFileDialog1.FileName
    End If
End Sub

and similarly for the other `Button.