How do I assign a null value to a SqlDataReader?

L

Learner

Hello,

This my a method to call a stored proce and uses a DataReader to read
the data

in the below method I am trying to assign a null value to my datareader
variable
Dim datareader As SqlDataReader
datareader = null
but it doesn't accept.
**********************************
Public Function GetDealers() As SqlDataReader
Dim strSql As String
Dim datareader As SqlDataReader
Try
Dim conn As IDbConnection = GetConnection()
Try
Dim cmd As IDbCommand = conn.CreateCommand()
strSql = "USP_GetDealers"
cmd.CommandText = strSql
cmd.CommandType = CommandType.StoredProcedure
conn.Open()
datareader =
cmd.ExecuteReader(CommandBehavior.CloseConnection)
Finally
End Try
Catch ex As Exception
End Try
Return datareader
End Function
*************************************************


Can some one help me with this..
-L
 
S

Steve C. Orr [MVP, MCSD]

That would work in C#, but since you're using VB.NET you should set it to
Nothing instead of Null.
datareader = Nothing
 
G

Guest

I don't think you can, DataReader objects have to be instantiated by using an
ExecuteReader method.
 
L

Learner

Hello ,
Thans for the quick responses.

If I don't assign a default value a green line appears underneath the
'End Function' and when I mouse hover on it it says

'Function 'GetDealers' doesn't return a value on all code paths. Anull
reference could occur at run time when the result is used'

So like Steve mentioned I assigned it with Nothing and modified it
slightly

Public Function GetDealers() As SqlDataReader
Dim strSql As String
Dim datareader As SqlDataReader
datareader = Nothing
Try
Dim conn As IDbConnection = GetConnection()
Try
Dim cmd As IDbCommand = conn.CreateCommand()
strSql = "USP_GetDealers"
cmd.CommandText = strSql
cmd.CommandType = CommandType.StoredProcedure
conn.Open()
datareader =
cmd.ExecuteReader(CommandBehavior.CloseConnection)
Finally
End Try
Catch ex As Exception
End Try
Return datareader
End Function


executed the code and it works fine and also there is no green line
underneath the "End Function" as I have moved "Return datareader" out
of the Try Catch block.

Hope the way I am doing it looks perfectly alright. Please advise if
itsn't and how do I it. Because I want to do it right :) Offcourse all
of us.

Thanks
-L
 
S

Steve C. Orr [MVP, MCSD]

Yes, that is a perfectly valid design.
I do hope you plan to put something in the catch block though, otherwise you
should probably remove "ex as Exception" to help optimize the performance.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top