开发者

Public function in VB.NET

开发者 https://www.devze.com 2023-03-17 20:03 出处:网络
I want to write a global function for my whole project to use in every form. I tried creating a public module and create a public function, but when I call it to my form, it generates error.

I want to write a global function for my whole project to use in every form. I tried creating a public module and create a public function, but when I call it to my form, it generates error.

let say my global function is about connection to the database. Then when I call it, it says that the connection property is not initialized.

In my function file, I used:

 Imports System.Data.SqlClient
 Public Module Connection
    Dim myConnection As SqlConnection
    Public Sub ConnectToDatabase()
       myConnection = New SqlConnection(".............")
       myConnection.Open()
    End Sub
 End Module

And in my form, I used:

 Private Sub Form_Load(...........) Handles MyBase.Load
    ConnectToDatabase()   'I call the function here
    .............................开发者_开发百科..................
 End Sub

And this does not work. Thanks.


I suspect this has nothing to do with the fact that this is a public module or public function and everything to do with the fact that you aren't initialising your connection correctly.

Try the following code:

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 
0

精彩评论

暂无评论...
验证码 换一张
取 消