connecting using ADO.net

Seems to an abundance of newbies asking questions and im no different, just got VS2005 and trying to connect it to my SQLserver database so ive created a simple form which should just use windows authentication or the user name and password supplied to connect to the database. The function resides in a module and is passed the parameters of whether the user wishes to choose windows authentication or not in ByVal blnConnectionString As Boolean

my problem is with the finally statement where it throws up an "object reference not set to an instance of an object" error on the following line

If g_objConn.State <> ConnectionState.Open Then

why am i getting this ive not done object orientated since i did Java in uni a few years back but im reading up on it, but this is just driving me nuts!!!

The whole function reads as follows:

declare the connection object and error object (which ive not used) and then go into the function.

'Declare Public Objects

Public g_objConn As SqlClient.SqlConnection

Public g_objError As SqlClient.SqlError

Public Function EstablishConnection(ByVal strDSN As String, ByVal strLogin As String, ByVal strpassword As String, ByVal blnConnectionString As Boolean) As Boolean

'setup error handling

Dim strconnectionString As String

Try

strconnectionString = "Server=(local);database=" & strDSN & ";"

If blnConnectionString Then

strconnectionString = strconnectionString & "Integrated Security=false; User ID = " & strLogin & ";" & "Password =" & strpassword & ";"

Else

strconnectionString = strconnectionString & "Integrated Security=True"

End If

Using g_objConn As New SqlClient.SqlConnection(strconnectionString)

g_objConn.Open()

End Using

Catch ex As Exception

Dim strError As String

strError = ex.ToString

MsgBox(strError)

Finally 'check the state of the connection

If g_objConn.State <> ConnectionState.Open Then

EstablishConnection = False

Else

EstablishConnection = True

End If

End Try

End Function



Answer this question

connecting using ADO.net

  • Bojan

    g_objConn is not instantiated at that part of your code.

    g_objConn only exists within the scope of your Using statement:

    Using g_objConn As New SqlClient.SqlConnection(strconnectionString)

    g_objConn.Open()

    End Using

    The Using statement disposes of g_objConn once the block of code is finished.

    Regards,

    Dave



  • doug2008

    ive gotto make the object available outside the using statement, if i declare it as a new instance of sqlclient.sqlconnection(strconnectionstring) outside of the using block and then do a simple g_objconn.open on it without a using block then it should beavailable to the fianlly statement right

  • connecting using ADO.net