Quantcast
Channel: VBForums - ASP, VB Script
Viewing all articles
Browse latest Browse all 688

sqlparameters function error

$
0
0
I am getting the following error:
Unable to cast object of type 'System.Boolean' to type 'System.Data.SqlClient.SqlParameter'.

Is there a better way of passing a parameters to a generic function and run it and return scalar value?

Code:

    Function GetEmail(ByVal iID As Integer, ByVal iTypeCD As Integer) As String
        Dim sRetVal As String = ""
        Dim cParameters As List(Of SqlParameter) = New List(Of SqlParameter)
        Dim sSQL As String = ""
Dim SqlCommandType As CommandType


        Select Case iTypeCD
            Case 1
                sSQL = "SELECT Email FROM table1 WHERE field_ID = @field_ID"
                Dim sqlparam1 As SqlParameter = New SqlParameter("@field_ID", SqlDbType.Int)
                sqlparam1.Value = iID
                cParameters.Add(sqlparam1)
                SqlCommandType = CommandType.Text
                sRetVal = GetVarcharField(sSQL, cParameters, SqlCommandType)
            Case 2
                sSQL = "SELECT Email FROM table2 WHERE field2_ID = @field2_ID"
                Dim sqlparam1 As SqlParameter = New SqlParameter("@field2_ID", SqlDbType.Int)
                sqlparam1.Value = iID
                cParameters.Add(sqlparam1)
                SqlCommandType = CommandType.Text
                sRetVal = GetVarcharField(sSQL, cParameters, SqlCommandType)
        End Select

        Return sRetVal
    End Function

Code:

    Function GetVarcharField(ByVal sSQL As String, _
                        oSqlParameters As List(Of SqlParameter), _
IncomingCommandType As CommandType) As String
        '--------------------------------------------------------------------
        ' Run query and return value
        '--------------------------------------------------------------------
        Dim sRetVal As String = ""
        Using conn As New SqlConnection(DBConn)
            Using sqlCmd As SqlCommand = New SqlCommand(sSQL, conn)
                sqlCmd.CommandType = IncomingCommandType
                sqlCmd.Parameters.AddRange(oSqlParameters.ToArray())

                Try
                    conn.Open()
                    sRetVal = sqlCmd.ExecuteScalar()
                Catch ex As Exception
                    _Error = "ERROR: " & ex.ToString
                Finally
                    sqlCmd.Dispose()
                    conn.Close()
                End Try
            End Using
        End Using

        Return sRetVal
    End Function

UPDATE: I updated my code to what I got working.

Viewing all articles
Browse latest Browse all 688

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>