I'm trying to develop a Webform where the user can filter and update SQL Server tables through queries with multiple values.
How it works
The user enters multiple values where each value is separated by a space on a textbox. Once all values are given the user clicks the execute button which replaces all the spaces with a comma and assigns the values to a single string variable. Then the query will filter for all the values contained within that variable.
Problem
The program insert the variables into the query as: 1000000,1000001
.
I also made a manual test with as follows: '1000000','1000001'
.
But for both attempts I get the following error:
Incorrect syntax near '1000000'
Question
How do I correctly pass multiple values within a variable in a query?
My code:
Protected Sub ExecuteButton_Click(sender As Object, e As EventArgs) Handles ExecuteButton.Click
Dim testString As String = ArticleTextbox.Text
Dim arrayOfTests As String() = testString.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries)
Dim newString As String = String.Join(", ", arrayOfTests)
Label2.Text = newString
'SQL.AddParam("@StyleID ", newString)
Try
dt = SQL.ExecQuery("Select STYLE_ID from ItemWebCategory where STYLE_ID in " & newString & "")
'dt = SQL.ExecQuery("Select STYLE_ID from ItemWebCategory where STYLE_ID in @StyleID")
Catch ex As Exception
MsgBox(ex.Message)
End Try
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
SqlControl
class:
Public Class SQLControl
Private ReadOnly ConStr As String = "connection String "
Private DBCmd As SqlCommand
'Query Parameters
Public Params As New List(Of SqlParameter)
'This generates a blank sqlclient class with the deafult connection string
Public Sub New()
End Sub
'Allow connection string override
Public Sub New(connectionString As String)
ConStr = connectionString
End Sub
'Execute Query Sub
Public Function ExecQuery(query As String) As DataTable
Dim DBDT = New DataTable
Using DBCon As New SqlConnection(ConStr),
DBCmd As New SqlCommand(query, DBCon)
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
Params.Clear()
DBCon.Open()
DBDT.Load(DBCmd.ExecuteReader)
End Using
Return DBDT
End Function
'Add variable as Paramerized objects
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New SqlParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class