Boneyflesh Boneyflesh - 3 months ago 9
Vb.net Question

Making a public Module

I'm using Visual Studio 2015 and I'm trying to make a module so my db2 connection will be public.

It's similar to a login procedure.

Here's my login CODE1

Imports IBM.Data.DB2
Public Class LoginForm
Dim dbConn As Common.DbConnection
Private Sub BtnLogin_Click(sender As Object, e As EventArgs) Handles
BtnLogin.Click
Dim user As String
Dim pass As String

user = Me.txtUser.Text
pass = Me.txtPass.Text

dbConn = New DB2Connection("server = localhost; database = hotel;" + "uid = '" & user & "'; password='" & pass & "';")
dbConn.Open()
If dbConn.State = ConnectionState.Open Then
Try

Main_Menu_Form.Show()
Me.Hide()
Catch ex As Exception
MsgBox(e.ToString)
End Try
End If
End Sub


and here's what I wrote in the module (which won't work) CODE2

Module Module1
Public dbConn As Common.DbConnection
End Module


I want the connection to be available on a different form.

This is my CODE3

Private Sub BtnLogin_Click(sender As Object, e As EventArgs) Handles BtnLogin.Click
If dbConn.State = ConnectionState.Open Then
Try
Dim str As String = "select * from table(EMPLOYEEDISP(20)) as udf"
Dim cmd As DB2Command = New DB2Command(str, dbConn)
Dim rdr As DB2DataReader
rdr = cmd.ExecuteReader

DGVEx.ColumnCount = 5
DGVEx.Columns(0).Name = "Employee Number"
DGVEx.Columns(1).Name = "Name"
DGVEx.Columns(2).Name = "Position"
DGVEx.Columns(3).Name = "Username"
DGVEx.Columns(4).Name = "Password"


Dim row As String()

While rdr.Read()
row = New String() {rdr.GetString(0), rdr.GetString(1), rdr.GetString(2), rdr.GetString(3), rdr.GetString(4)}
DGVEx.Rows.Add(row)
End While
MsgBox("Executed")
Catch ex As Exception
MsgBox(e.ToString)
End Try
End If




End Sub


Here's the error I got from CODE3


An unhandled exception of type 'System.NullReferenceException' occurred in Hotel.exe

Additional information: Object reference not set to an instance of an object.


This may be because
dbConn.State
is not closed or not connected and I think there is something wrong with CODE2 (module).

What's the correct code to make a connection public in a module?

Answer

In CODE3 you need to initialize the dbConn. What happens is that you trying to access a property of uninitialized object - the meaning of the NullReferenceExeption. So do it as you did in CODE1:

dbConn = New DB2Connection("server = localhost; database = hotel;" + "uid = '" & user & "'; password='" & pass & "';")

Now you can check the State property.
However, I don't recommend this approach, especially if this is WEB application.

Use the connection object where it is actually needed AND dispose of it appropriately. The most robust way of doing this is through Using statement:

Using dbConn = New DB2Connection("server = localhost; database = hotel;" + "uid = '" & user & "'; password='" & pass & "';")
' Do your stuff...

End Using

Now you can be sure that the dbConn is disposed and there are no memory leaks.