Must declare the scalar variable @ID?

manny cash

Active member
Joined
Oct 19, 2024
Messages
26
Programming Experience
Beginner
I need to search in a table a specific record with a textbox, result in a label and display in a Gridview the whole record

This code is not mine; it belongs to somebody. I made some modifications, but I got an error, and I do not understand it. I am asking some of you guys for help interpreting the error message.
Here is the error: An error occurred: Must declare the scalar variable '@ID. Thank you in advance. God bless all of you.

VB.NET:
    ' Public Sub SearchfrmMain()

    Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
        ' Get the search term from the TextBox
        Dim searchTerm As String = txtSearch.Text

        ' SQL query to search for the record
        Dim query As String = "SELECT Company FROM Citas1 WHERE SearchColumn = @ID, @Company, @Contacts, @Telephone, @Address, @Email, @AppoDate @AppoTime, @Matters, @Solutions,"

        ' Create a connection and command
        Using connection As New SqlConnection(connectionString)
            Using command As New SqlCommand(query, connection)
                ' Add parameter to prevent SQL injection
                command.Parameters.AddWithValue("@Company", searchTerm)

                Try
                    ' Open the connection
                    connection.Open()

                    ' Execute the query and retrieve the result
                    Dim result As Object = command.ExecuteScalar()

                    ' Display the result in the Label
                    If result IsNot Nothing Then
                        lblResult.Text = result.ToString()
                    Else
                        lblResult.Text = "Record not found."
                    End If
                Catch ex As Exception
                    ' Handle any errors
                    MessageBox.Show("An error occurred: " & ex.Message)
                End Try
            End Using
        End Using

    End Sub
 
Last edited by a moderator:
Your SQL code contains 10 parameter placeholders but, according to the code you posted, you're only adding one parameter named @Company. What about @ID, @Contacts, ..., @Solutions?
 
Apart from that, your SQL code makes no sense. Your WHERE clause is malformed. It ends with a comma, which is wrong, and this makes no sense:
SQL:
SearchColumn = @ID, @Company, @Contacts, @Telephone, @Address, @Email, @AppoDate @AppoTime, @Matters, @Solutions
Did you actually mean to AND or OR multiple criteria, e.g.
SQL:
SearchColumn = @ID OR SearchColumn = @Company OR SearchColumn = @Solutions
If you explain what you're actually trying to achieve, we can probably explain how to achieve it.
 
Back
Top