Sophart
Sophart

Reputation: 67

How could I pass parameter to sqldataadapter?

I have tried to pass parameter a value, but what it returns is nothing. If I use a simple sql command without parameter I can retrieve all the data from my database. Here is my code:

Public Shared Function RetrieveData() As DataTable
    Connection.Open()
    Try
        sql = "SELECT DEP_ID AS CODE, DEP_NAME AS DEPARTMENT FROM DEPART_TBL WHERE " & FieldName & " LIKE N'%@criteria%'"
        da = New SqlDataAdapter
        da.SelectCommand = New SqlCommand(sql, Connection.SQLConnection)
        da.SelectCommand.Parameters.Add("@criteria", SqlDbType.NChar)
        da.SelectCommand.Parameters("@criteria").Value = "KCL"
        'da.SelectCommand.Parameters.Add("@criteria", SqlDbType.NChar, 10, "DEP_ID")
        'Message.ShowInfo(da.SelectCommand.CommandText.ToString)
        'Exit Function
        dt = New DataTable
        da.Fill(dt)
    Catch ex As Exception
        Message.ShowError(ex.Message)
    End Try
    da.Dispose()
    Connection.Close()
    Return dt
End Function

Upvotes: 2

Views: 1967

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460258

You are searching the string @criteria, you want to use the parameter, so use:

sql = "SELECT DEP_ID AS CODE, DEP_NAME AS DEPARTMENT FROM DEPART_TBL WHERE " & FieldName & " LIKE N'%' + @criteria + '%'"

or you can use it in the parameter:

da.SelectCommand.Parameters("@criteria").Value = "%KCL%"

Upvotes: 2

Related Questions