Solved

Object reference not set to an instance of an object

Posted on 2003-10-29
19
137,843 Views
Last Modified: 2011-08-18
I keep receiving "Object reference not set to an instance of an object" error when trying to run this code:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        Dim dtr As OleDbDataReader
        Dim strSQL As String = "Select * From Complex PracticeOral3"
        Dim clsDA As New DataAccess.DBConn()

        dtr = clsDA.getDataReader(strSQL)
        lblQuestion.Text = dtr("Question")
    End Sub

What am I doing wrong?
0
Comment
Question by:CodeDeamon
  • 7
  • 4
  • 2
  • +4
19 Comments
 
LVL 4

Expert Comment

by:NetPointer
ID: 9646948
it seems error is from DataAccess.DBConn class u r using..

check the DBConn ..it might not getting instantiated..so clsDA is nothing.

Regards.
NetPointer
0
 
LVL 3

Expert Comment

by:the-edge
ID: 9646954
change:

       Dim dtr As OleDbDataReader

in:

       Dim dtr As New OleDbDataReader

this should solve

the edge
0
 

Author Comment

by:CodeDeamon
ID: 9646959
NetPointer,

This is the class:

Public Class DBConn

    Public Shared Function getDataReader(ByVal sqlqry As String) As OleDbDataReader
        Dim Connstring As String = "blah" <--there is a connection string here
        Dim conn As New OleDbConnection(Connstring)
        Dim objcmd As New OleDbCommand(sqlqry, conn)
        Dim dtr As OleDbDataReader

        Try
            conn.Open()
            With objcmd
                .CommandType = CommandType.Text
            End With
            dtr = objcmd.ExecuteReader()
            Return dtr
        Catch ex As Exception

            'exception handling code to go here
        Finally
            dtr = Nothing
            objcmd = Nothing
        End Try
    End Function

End Class
0
 

Author Comment

by:CodeDeamon
ID: 9646962
Edge,

Says this when compiled:

 'System.Data.OleDb.OleDbDataReader.Private Overloads Sub New(connection As System.Data.OleDb.OleDbConnection, command As System.Data.OleDb.OleDbCommand, depth As Integer, chapter As System.IntPtr)' is not accessible in this context because it is 'Private'.
0
 
LVL 3

Expert Comment

by:the-edge
ID: 9646970
sorry, ignore the previous post. consider this:

after the line:

        dtr = clsDA.getDataReader(strSQL)

call the read method of the DataReader:

       dtr.Read()

the edge
0
 

Author Comment

by:CodeDeamon
ID: 9646981
lol......ahhhh....well in my inifinite wisdon I was trying to pull data from a empty database, but now it is throwing errors on:

dtr = clsDA.getDataReader(strSQL)
lblQuestion.Text = dtr("Question")

Saying:

'System.Data.OleDb.OleDbDataReader' cannot be converted to '1-dimensional array of System.Data.OleDb.OleDbDataReader'.
AND
Value of type 'System.Data.OleDb.OleDbDataReader' cannot be converted to 'String'.
Respectively.

I shall research, but if you guys no what this means, I would appreciate it.

0
 
LVL 4

Expert Comment

by:NetPointer
ID: 9647071
may be declaration of dtr is wrongly done declared as an array...

and also try putting dtr("Question").tostring

may be this helps.

Regards.
Netpointer
0
 

Author Comment

by:CodeDeamon
ID: 9647243
Man, this is frustrating.  All I am trying to do is pass in a query string and have it return a datareader.  I have created the DataAccess class as a vb project, and then added it as a refernce to my asp.net project.  THis is all the code for the class:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class DBConn

    Public Sub New()

    End Sub

    Public Function getDataReader(ByVal sqlqry As String) As OleDbDataReader
        Dim Connstring As String = "blah" <--there is a connection string here
        Dim conn As New OleDbConnection(Connstring)
        Dim objcmd As New OleDbCommand(sqlqry, conn)
        Dim dtr As OleDbDataReader

        Try
            conn.Open()
            With objcmd
                .CommandType = CommandType.Text
            End With
            dtr = objcmd.ExecuteReader()
            Return dtr
        Catch ex As Exception
            'exception handling code to go here
        Finally
            dtr = Nothing
            objcmd = Nothing
            conn.Close()
        End Try
    End Function

End Class

That's all of it.  Then this is my call in the code_behind of my webform:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim clsDA As New DataAccess.DBConn()

        Dim dtr As OleDbDataReader = clsDA.getDataReader("Select * From Complex PracticeOral6")
        lblQuestion.Text = dtr("Question") <----back to the original error:Object reference not set to an instance of an object

    End Sub

If anyone knows what I am doing wrong I would greatly appreciate it.
0
 
LVL 5

Expert Comment

by:arvindb1
ID: 9647856
try these two things.
First in your getDataReader function in your dbconn class above dont close the connection i.e. under Finally block remove the line conn.Close()

Secondly in your webform page_load
instead of lblquestion.text=dtr("Question")
put this code
while dtr.read
   lblquestion.text=dtr("Question")
end while
dtr.close()

Hope it helps
Arvind
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 12

Expert Comment

by:farsight
ID: 9649565
This code bugs me (though I'm not sure it's the problem):

        Try
            ' blah blah ...
            dtr = objcmd.ExecuteReader()
            Return dtr
        Catch ex As Exception
            'exception handling code to go here
        Finally
            dtr = Nothing
            ' blah blah ...
        End Try

"Finally" means it's ALWAYS executed, but "Return" means leave the routine.   I suspect dtr is ALWAYS being set to nothing before it's returned!   Try something like this instead:

        Try
            ' blah blah ...
            dtr = objcmd.ExecuteReader()
            ' *** Don't return here.
        Catch ex As Exception
            'exception handling code to go here
        Finally
            ' *** Do NOT set dtr to nothing here.  Close it instead.  
            ' *** Let the garbage collector release the object.
            dtr.Close()
            ' blah blah ...
        End Try
        Return dtr

References:

http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemDataOleDbOleDbDataReaderClassCloseTopic.asp?frame=true
"You must explicitly call the Close method when you are through using the OleDbDataReader to use the associated OleDbConnection for any other purpose."
0
 

Author Comment

by:CodeDeamon
ID: 9654359
All right, I think we are getting closer to the problem.  Farsight, I took your advice and changed the function to:

Public Function getDataReader(ByVal sqlqry As String) As OleDbDataReader
        Dim Connstring As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Inetpub\wwwroot\BusinessApplication\DB\ISM3232.mdb"
        Dim conn As New OleDbConnection(Connstring)
        Dim objcmd As New OleDbCommand(sqlqry, conn)
        Dim dtr As OleDbDataReader

        Try
            conn.Open()
            With objcmd
                .CommandType = CommandType.Text
            End With
            dtr = objcmd.ExecuteReader()
        Catch ex As Exception
            'exception handling code to go here
        Finally
            dtr.Close()
        End Try

        Return dtr
    End Function

Now, I get the "Object reference not set to an instance of an object" on the dtr.Close().  So, what seems to be the problem.  I have used this code in other areas and it has worked fine.  A bit confused by this one.
0
 

Author Comment

by:CodeDeamon
ID: 9654727
If there is any more ideas I what greatly appreciate it......I am at a lose on this one.......
0
 
LVL 5

Expert Comment

by:arvindb1
ID: 9656188
dont close dtr in your above function i.e. remove dtr.close() from above function and give it only after you finished reading the data i.e. after

while dtr.read
   lblquestion.text=dtr("Question")
end while
dtr.close()
0
 
LVL 12

Accepted Solution

by:
farsight earned 200 total points
ID: 9657295
Yes, arfvindb1, that's right.  Thanks for the assist.
Doh!  Silly oversight of me to close the obj before it's used.

Even if dtr.close() was needed, it should have had:
  If Not (dtr Is Nothing) Then dtr.close()
Why? Because dtr would be Nothing if the execution path went through the Catch block.

CodeDeamon,
  If you get "Object reference not set to an instance of an object" on the dtr.Close(), that means that the dtr object never got set to an object in the statement "dtr = objcmd.ExecuteReader".  That means something isn't right in the setup of the command object, perhaps the SQL query, perhaps the connection, perhaps something else.  Test to find the ultimate cause.

Temporarily put a line like this in the Catch block, so you know when this error happens.
  Console.Writeline("Error initializing dtr")
It's always dangerous to have a blank error handler.  What purpose would it serve?  Make sure do don't leave that in your final project, and put in real exception handling code.
0
 
LVL 12

Expert Comment

by:farsight
ID: 9657357
Off Topic Followup:

higginspi (in a message elsewhere said):
"... free Premium Service (PS) by first obtaining 10,000 expert points  and then maintaining 3,000 expert points per month.  You can also skip a month and still keep PS as long as you make 3,000 points within the next month."

I'm at 2997 now.  I need only 3.
I'd appreciate if you'd assign me some points TODAY (Oct 31, Halloween), before the end of the month!

Thanks.
0
 

Author Comment

by:CodeDeamon
ID: 9657457
Farsight,

I will give the points to you since you have stuck with it for so long trying to help me, but if I still have a problem I still might need your help!!!  I do appreciate all the help.
0
 
LVL 12

Expert Comment

by:farsight
ID: 9657517
Thanks!
0
 
LVL 2

Expert Comment

by:anwar ul haque
ID: 11569256
Dim strCon As String = "workstation id=DEV024;packet size=4096;integrated security=SSPI;data source=DEV024;persist security info=True;initial catalog=pubs"
        'Provide appropritate string other wise exception occurs and you have to write it into try ..catch block
        Dim sqlCon As New SqlClient.SqlConnection(strCon)
        Dim sqlCMD As New SqlClient.SqlCommand("select au_id from authors where au_lname = 'White'", sqlCon)
        Dim sqlReader As SqlClient.SqlDataReader
        Try

            sqlCon.Open()
        sqlReader = sqlCMD.ExecuteReader
            Do While sqlReader.Read
                'do your job here'Ive just add lbl
                lbl.Text = sqlReader.GetString(0)
            Loop
        Catch ex As Exception
            'Catch Exception here
            lbl.Text = ex.Message
        Finally
            'Finally dispose
            sqlReader.Close()
            sqlCon.Close()
            sqlCon = Nothing
            sqlCMD = Nothing
            sqlReader = Nothing
        End Try
0
 

Expert Comment

by:timecomplexity
ID: 12157513
Hello,
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now