Search code examples
sqlvb.netsql-like

error when I use query with like in vb.net


there are an error when i use like in my query, the error when i use quotation (') only this my code

zz = "SELECT * from users where userid Like  N'%" & TextBox1.Text & "%'"
Dim cmdz As SqlCommand = New SqlCommand(zz, myConnection2)
zr = cmdz.ExecuteReader
DataGridView1.Rows.Clear()
If zr.HasRows Then
    While zr.Read
        Dim rowall As String() = New String() {zr("customer").ToString, zr("Management").ToString, zr("block").ToString, zr("Customerid").ToString}
        DataGridView1.Rows.Add(rowall)
    End While
    DataGridView1.Visible = True
End If

Solution

  • Use parameters which will convert your input into valid sql query (so you don't have to escape single quotes)

    zz = "SELECT * from users where userid Like  N'%' + @userId +'%'"
    Dim cmdz As SqlCommand = New SqlCommand(zz, myConnection2)
    cmdz.Parameters.Add("@userId", SqlDbType.VarChar).Value = TextBox1.Text