3

I want to create a global function to use throughout my application. Let say it's about the connection to the database.

My code that i plan to use in my global function is:

myConnection = New SqlConnection("...........")
 myConnection.Open()

So that I can call it to use in every form throughout my application. This can make me easy to edit the connection later.

Could anyone help me show how to define this global function and how to call this function in the form.

Best regard,

Tepken Vannkorn
  • 9,648
  • 14
  • 61
  • 86
  • 1
    For a discussion of Modules vs. Classes with shared members see: http://stackoverflow.com/questions/881570/classes-vs-modules-in-vb-net – Heinzi Jul 07 '11 at 10:24

2 Answers2

4
Public NotInheritable Class Utilities

Private Sub New()
End Sub

Public Shared Function MyMethod(myParam As Object) As MyObject
    'Do stuff in here
    Return New MyObject()
End Function

 End Class

And then to consume

Dim instance As MyObject = Utilities.MyMethod(parameterObject)
Paulie Waulie
  • 1,690
  • 13
  • 23
2

Use Module instead of class

Module ConnectionHelper
    Public Function OpenConnection() As SqlConnection
        Dim conn As New SqlConnection("")
        conn.Open()
        Return conn
    End Function
End Module

Class P
    Public Sub New()
        Using conn = OpenConnection()
            'here you can work with connection
        End Using
    End Sub
End Class

In class P you have showcase of prefered usage

Ales Ruzicka
  • 2,770
  • 1
  • 18
  • 24