Link to home
Start Free TrialLog in
Avatar of CodeManiac
CodeManiac

asked on

Function to Return DataSet

I want to write a function to return the results of a SQL query as a dataset. I'm calling it like this:

Dim dsResults As Data.DataSet = New Data.DataSet
dsResults = databaseFunctions.ExecuteQuery("SELECT * FROM tUsers")

But I keep getting this error on the second line:
System.NullReferenceException: Object reference not set to an instance of an object.


Function ExecuteQuery(ByVal txtQuery As String) As Data.DataSet
        OpenDB()
        cmd = New SqlClient.SqlCommand
        adItem = New SqlClient.SqlDataAdapter
        dsResults = New Data.DataSet
        cmd = New SqlClient.SqlCommand(txtQuery, cn)
        adItem.SelectCommand = cmd
        adItem.Fill(dsResults)
        ExecuteQuery = dsResults
        CloseDB()
End Function



ASKER CERTIFIED SOLUTION
Avatar of Torrwin
Torrwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
is option explicit turned off?
Avatar of CodeManiac
CodeManiac

ASKER

Thanks Torrwin!

Can you give an example of how you call your function?

Do you declare a dataSet variable like I tried above?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Paul is right, that's how I essentialy do it:

Dim ds as New Dataset
Dim sSQL as String
sSQL = "SELECT * FROM AUTHORS"
ds = SelectCommand(sSQL)

I'm getting an "Object reference not set to an instance of an object." error when I call the function like this...


Dim ds As Data.DataSet = New Data.DataSet
        ds = databaseFunctions.SelectCommand("SELECT * FROM tUsers")
        With ds.Tables(0)
            For i = 0 To .Rows.Count - 1
                Response.Write("test" & i)
            Next
        End With

Any ideas?

Post your answer at the following URL to get another 500 points...
https://www.experts-exchange.com/questions/21393393/Object-reference-not-set-to-an-instance-of-an-object.html

Thanks!