-1

How To Make public sub form ShowDialog

I have Module and i want to put a code that i can use it in all project to open forms .

I have Tried to put this code in Module Put Not Working

Public Sub OpenForm(ByVal Frm As Form)
    Frm = New Frm()
    frm.ShowDialog()
End Sub

The Error Is " Type 'Frm' is not defined "

Kind Regards And Thanks For Help Salem

Salem
  • 87
  • 1
  • 2
  • 7

2 Answers2

2

You could write your sub to show a dialog

Public Module MyModule

    Public Sub OpenForm(ByVal Frm As Form)
        frm.ShowDialog()
    End Sub

End Module

which would be called like this

Dim myForm = New Form()
MyModule.OpenForm(myForm)

But it would be much easier to just do

Dim myForm = New Form()
myForm.ShowDialog()

EDIT

Here is a generic version which constructs and disposes the form since it is used modally

Public Module MyModule

    Public Sub OpenForm(Of T As {Form, New})()
        Using frm As New T()
            frm.ShowDialog()
        End Using
    End Sub

End Module

which would be called like this

MyModule.OpenForm(Of Form)()
' or with your custom form class
MyModule.OpenForm(Of MyCustomFormClass)()
djv
  • 15,168
  • 7
  • 48
  • 72
  • 1
    When using .ShowDialog it is advised to create the instance of form in a Using block so the form is properly disposed when it's closed, unless there is a reason you want to leave it undisposed, which I cannot think of any. – Mr. Tripodi Apr 25 '19 at 15:50
  • 1
    @Mr.Tripodi It's a good point but I'm not sure if it falls within the scope of the question. Especially because of the ambiguity in where the form is constructed in OP's original question. But I will add another method which disposes the modal form after use. – djv Apr 25 '19 at 16:03
  • I was actually unable to infer the scope of the question, nice edits though, looks good – Mr. Tripodi Apr 25 '19 at 16:50
  • Thank You All But Still small issue which is when add this code OpenForm(Of Frm_CountiresAndCitiesDetails)() Frm_CountiresAndCitiesDetails.TextBox1.Text = Val(p.Get_Last_Counrty) The TextBox1 in the Frm_CountiresAndCitiesDetails get no information from database Val(p.Get_Last_Counrty) this is to get max id in database Thanks – Salem Apr 26 '19 at 04:50
  • That is because you open it modal and that is a blocking call which means your code stops on `ShowDialog()` inside the method until the form is closed, and anything done after it outside the method is done after it is disposed. It looks like you can't use the method I provided in my edit after all. Also you seem to accessing the [default form instance of vb.net](https://stackoverflow.com/a/4699360/832052) which is not advised. – djv Apr 26 '19 at 15:08
0

In the module

Public Sub ShowADialog()
    Dim dialog As New SaveFileDialog
    dialog.ShowDialog()
End Sub

In the form

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ShowADialog()
End Sub
Mary
  • 14,926
  • 3
  • 18
  • 27