Object reference not set to an instance of an object

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?
CodeDeamonAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

NetPointerCommented:
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
the-edgeCommented:
change:

       Dim dtr As OleDbDataReader

in:

       Dim dtr As New OleDbDataReader

this should solve

the edge
0
CodeDeamonAuthor Commented:
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
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

CodeDeamonAuthor Commented:
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
the-edgeCommented:
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
CodeDeamonAuthor Commented:
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
NetPointerCommented:
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
CodeDeamonAuthor Commented:
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
arvindb1Commented:
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
farsightCommented:
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
CodeDeamonAuthor Commented:
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
CodeDeamonAuthor Commented:
If there is any more ideas I what greatly appreciate it......I am at a lose on this one.......
0
arvindb1Commented:
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
farsightCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
farsightCommented:
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
CodeDeamonAuthor Commented:
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
farsightCommented:
Thanks!
0
anwar ul haqueCommented:
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
timecomplexityCommented:
Hello,
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.