joe joe - 4 months ago 32
Vb.net Question

Creating a global database connection on an mdi form

In my vb project, I have an mdi parent form to open other forms. On one form I have a datagridview displaying a table that I made in sql server. The data loads fine if I set up the connection locally (on the form load with the DGV), but I was told to make the connection global to keep it simpler and stop it getting a bit confusing. I added the code to the mdi form, as below.

Public Class mdi1

Dim con As inifile = New inifile()
Dim constr = con.readconnectionstring()


I've already added the
Imports System.Data.OleDb
code, so why do I get the following error when compiling the code?

constr is not declared, it may be inaccessible due to its protection level


This error is in my form1_load subroutine (where the connection was originally being set to load the data to the DGV)

Answer

As you appear to be a beginner I will try to tell you how to get this working, rather than best practise.

ensure your constr is accessible from anywhere by defining it in your MDI form as Public:

Public constr = con.readconnectionstring()

Now you can access this anywhere by using the fully qualified variable name:

mdi1.constr

Best practise would be probably to store this in its own class rather than the MDI form

Comments