jake123 jake123 - 1 month ago 9
Vb.net Question

Creating a Open File Dialog Function to be used multiple times

I have this piece of code that I would like to make it into a function so I can reuse it by changing some parameters.

So this is what I have so far

Sub OpenFiles(InFile As IO.StreamReader, verifytheFileName As String,dialogBoxTitle As String)
Dim result As DialogResult
Dim FilePath As String
Dim FileName As String

Try
dialogBox1.Title = dialogBoxTitle
dialogBox1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
result = dialogBox1.ShowDialog 'Open This Dialog Box
FilePath = dialogBox1.FileName 'Gets the Path of the file and stores it in File Path Varible
FileName = dialogBox1.SafeFileName 'Gets the name of the file and stores it in File Name Varible

If Not FileName = verifytheFileName Then
MessageBox.Show("Please Select " &verifytheFileName)
dialogBox1.Reset()
Else
InFile = IO.File.OpenText(FilePath)
End If
Catch ex As Exception
MessageBox.Show("ERROR")
End Try

End Sub


So the only thing I am unable to do is to change the
dialogBox1
text in to
dialogBox2
or
dialogBox3
.

Please advice on how can I get this done

Answer

Pass the dialogbox in parameters function

Sub OpenFiles(InFile As IO.StreamReader, verifytheFileName As String,dialogBoxTitle As String, dialogBox1 as System.Windows.Forms.SaveFileDialog)
Dim result As DialogResult
Dim FilePath As String
Dim FileName As String

Try
    dialogBox1.Title = dialogBoxTitle
    dialogBox1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*" 
    result = dialogBox1.ShowDialog 'Open This Dialog Box
    FilePath = dialogBox1.FileName 'Gets the Path of the file and stores it in File Path Varible
    FileName = dialogBox1.SafeFileName 'Gets the name of the file and stores it in File Name Varible

    If Not FileName = verifytheFileName Then
        MessageBox.Show("Please Select " &verifytheFileName)
        dialogBox1.Reset()
    Else
        InFile = IO.File.OpenText(FilePath)
    End If                  
Catch ex As Exception
    MessageBox.Show("ERROR")
End Try

End Sub