我想为整个项目编写一个全局函数,以便在每种形式中使用。我尝试创建一个公共模块并创建一个公共函数,但是当我将它调用到我的表单时,它会生成错误。
假设我的全局函数是关于数据库的连接。然后,当我调用它时,它表示连接属性未初始化。
在我的函数文件中,我使用了:
Imports System.Data.SqlClient
Public Module Connection
Dim myConnection As SqlConnection
Public Sub ConnectToDatabase()
myConnection = New SqlConnection(".............")
myConnection.Open()
End Sub
End Module
在我的表格中,我使用了:
Private Sub Form_Load(...........) Handles MyBase.Load
ConnectToDatabase() 'I call the function here
...............................................
End Sub
这不起作用。 感谢。
答案 0 :(得分:1)
我怀疑这与公共模块或公共功能无关,而且与您未正确初始化连接的事实有关。
请尝试以下代码:
Imports System.Data.SqlClient
Imports System.Data
Public Sub ConnectToSQL()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=atisource;Initial Catalog=BillingSys;Persist Security Info=True;User ID=sa;Password=12345678"
con.Open()
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message) Finally
con.Close() 'Whether there is error or not. Close the connection.
End Try
End Sub