Thursday, March 22, 2012

Taking a value from a dataset

I trying to get a single values from a dataset however I keep getting the following error please help

 Function get_poll_questions() As System.Data.DataSet

Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=db\database.mdb"
Dim dbConnection As System.Data.IDbConnection = New System.Data.OleDb.OleDbConnection(connectionString)

Dim queryString As String = "SELECT top 1 * FROM tbl_poll_questions ORDER BY pol_question, rnd(pol_ID)"
Dim dbCommand As System.Data.IDbCommand = New System.Data.OleDb.OleDbCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim dataAdapter As System.Data.IDbDataAdapter = New System.Data.OleDb.OleDbDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim dataSet As System.Data.DataSet = New System.Data.DataSet
dataAdapter.Fill(dataSet)

strTESTING = DataSet.Tables("tbl_poll_questions").Rows(0)("pol_question").ToString()

return strTesting

End Function

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 116:
Line 117:
Line 118: strTESTING = DataSet.Tables("tbl_poll_questions").Rows(0)("pol_question").ToString()
Line 119:
Line 120: return strTesting

Many thanks in advanceMake sure that the SQL has returned any data. Also make sure that pol_question is the correct name of the column.
Also, I havent seen it done like this:

strTESTING = DataSet.Tables("tbl_poll_questions").Rows(0)("pol_question").ToString()

Try this instead:

strTESTING = DataSet.Tables("tbl_poll_questions").Rows(0).items("pol_question").ToString()

Also, since you are doing this:
dataAdapter.Fill(dataSet)

and not giving a table name...the table is not named "tbl_poll_questions". Rather, it is named just "table" or you could use the index of 0, like:

strTESTING = DataSet.Tables(0).Rows(0).items("pol_question").ToString()

In order to use that table name you would have to do:
dataAdapter.Fill(dataSet,"tbl_pol_questions")

MajorCats

0 comments:

Post a Comment