Lefteris Gkinis
Lefteris Gkinis

Reputation: 1259

Object variable not set with an instance of an object

Just because (in my code) some times looks the sqlDataReader to be open and tells me that "there is already an open data reader"
I decide to put this line: If Not SqlReader.IsClosed Then SqlReader.Close()

Select Case PreviousRecord
    Case True
        SqlComm = New SqlCommand("Select * from " & tmpName & " where FuelOrderValid = '" & True & "' Order by FuelLoadDate", ReportsSQLConn)
    Case False
        SqlComm = New SqlCommand("Select * from " & tmpName & " where FuelOrderValid = '" & True & "' And FuelOrderID = '" & ordNum & "' Order by FuelLoadDate", ReportsSQLConn)
End Select      

If Not SqlReader.IsClosed Then SqlReader.Close()

If SqlComm.Connection.State = Data.ConnectionState.Open Then
    SqlReader = SqlComm.ExecuteReader(CommandBehavior.KeyInfo)
Else
    SqlComm.Connection.Open()
    SqlReader = SqlComm.ExecuteReader(CommandBehavior.KeyInfo)
End If

But now, when it comes to execute the instruction
If Not SqlReader.IsClosed Then SqlReader.Close()
It gives the error:
Object Variable Not Set To An Instance Of An Object
I really can't understand why is doing this.
Please is there anybody to assist me?

Upvotes: 1

Views: 413

Answers (1)

Geoff Appleford
Geoff Appleford

Reputation: 18832

The SqlReader has not been initialised before calling SqlReader.IsClosed and SqlReader.Close. You can check whether its nothing like this:

If SqlReader IsNot Nothing Then
    ' Do something with the SqlReader'
Else
    ' Create a new SqlReader'
End If

Upvotes: 4

Related Questions