Bobski Bobski - 3 years ago 175 Question

Vb.Net setting connection in Module

I'm creating a new Vb.Net project and I'm looking to create a module that will fire up when project is run so that the connection is set. I created a new module called Connection and placed the following code there...

Imports System.Data.SqlClient
Module Connection
Sub main()
Dim sConnection As String = "Data Source=Van;Initial Catalog=OP;User ID=userid;Password=password"
End Sub
End Module

And now in my Form1 I added the SQLConnection component and attempt to do something like this....

Using Con as New SQLConnection(sConnection)

'but this does not seem to work. The connection string works properly since it's fully working if I include it in the form itself.

Any particular reason why this is happening? Also, say I have 30 forms in the app, do I need to add the SqlConnection component to each form that will need to talk to the DB?

Answer Source

The "Main()" is a function. And you declared a local variable "sConnection".

Your Form is another class.

A class can access only its members, global members or global static members (or some friend scenarios like C++).

Take out that declaration from "Main", either declare in the scope of your Form or declare it as a global variable, where your form can access.

Or put your connection string in a config file and read from it. (easy to configure at later point of time.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download