Reputation: 4069
Hoping for a quick answer here.
OK, since I do a lot of single value lookups from the DB, I created a function to handle the lookup for me. It's designed to get any type of data type (string, integer, date, ...).
It works when I want to retrieve a number, but gives me an error when I want a string (InvalidCastException trying to convert a string to an integer on the line: GetValue = DR(0)). I can't do a ctype or directcast because the datatype is unknown and varies. Haven't tested any other data types yet.
Code is below. I'd like to find out how to make this function work, or pointed to another function that will serve the same purpose.
Public Shared Function GetValue(Optional ByVal SQL As String = "", Optional ByVal FieldName As String = "", Optional ByVal TableName As String = "", Optional ByVal WhereClause As String = "") As VariantType?
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim strSQL As New SQLStringBuilder
Dim DR As SqlDataReader
myConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnAFRAMSSQL").ConnectionString)
strSQL.Add(SQL)
If FieldName > "" Then
strSQL.Add("SELECT " & FieldName)
End If
If TableName > "" Then
strSQL.Add("FROM " & TableName)
End If
If WhereClause > "" Then
strSQL.Add("WHERE " & WhereClause)
End If
myConnection.Open()
myCommand = New SqlCommand(strSQL.ToString, myConnection)
DR = myCommand.ExecuteReader()
If DR.HasRows Then
DR.Read()
GetValue = DR(0)
Else
GetValue = Nothing
End If
End Function
Thanks.
Upvotes: 1
Views: 749
Reputation: 94643
You may specify the System.Object
(System.Object is the ultimate base class of all types) return type of your method.
Public Shared Function GetValue(Optional ByVal SQL As String = "", Optional ByVal FieldName As String = "", Optional ByVal TableName As String = "", Optional ByVal WhereClause As String = "") As Object
Dim myConnection As SqlConnection
....
Dim obj as Object=Nothing
If DR.Read()
obj=DR(0)
End If
DR.Close()
myConnection.Close()
return obj
End Function
Upvotes: 2