在文本框中搜索名称不起作用“语法不正确” [英] Searching name in textbox not work "incorrect syntax"

查看:91
本文介绍了在文本框中搜索名称不起作用“语法不正确”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在尝试使用文本框搜索姓名,而不是搜索



我尝试了什么:



Hi I am trying to search name using text box and it is not searching

What I have tried:

protected void txt_SearchName_TextChanged1(object sender, EventArgs e)
       {
           cn.Open();
           SqlCommand cmd = new SqlCommand("select * from gvdetails17 where EmpName LIKE % '" + txt_SearchName.Text + "'%", cn);
           DataTable dt = new DataTable();
           SqlDataAdapter da = new SqlDataAdapter(cmd);
           da.Fill(dt);
           gvDetails.DataSource = dt;
           cn.Close();
       }




<pre> <asp:TextBox ID ="txt_SearchName" runat="server" style="margin-bottom: -71px;
 margin-left:308px" Width="120px" Font-Size="12px" OnTextChanged= "txt_SearchName_TextChanged1" AutoPostBack="false"></asp:TextBox>

推荐答案

尝试

try
protected void txt_SearchName_TextChanged1(object sender, EventArgs e)
     {
             string name = txt_SearchName.Text.Trim();
             if(name != "") {
             SqlCommand cmd = new SqlCommand("select * from gvdetails17 where EmpName Like '%'+ @name + '%' ", cn);
             cmd.Parameters.Add("@name", name);
             DataTable dt = new DataTable();
             SqlDataAdapter da = new SqlDataAdapter(cmd);
             da.Fill(dt);
             gvDetails.DataSource = dt;
             gvDetails.DataBind();

         }
     }


百分比通配符必须在引号内:

The percentage wildcard characters must be inside the quotes:
SqlCommand("select * from gvdetails17 where EmpName LIKE '% " + txt_SearchName.Text + "%'", cn);


永远不要这样做!永远不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。



此外,引用位置错误。

使用参数化查询的可能性会删除你的问题 - 并且不要忘记你的其余代码:一个错过的命令,任何人都可以删除你的数据库。

Never do that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

Additionally, the quote is in the wrong place.
The chances are that using a parameterised query will remove your problem - and don't forget the rest of your code: one missed command and anyone can delete your database.
using (SqlCommand cmd = new SqlCommand("SELECT * FROM gvdetails17 WHERE EmpName LIKE '%' + @Txt + '%'", cn))
   {
   cmd.Parameters.AddWithValue("@Txt", txt_SearchName.Text);
   ...


这篇关于在文本框中搜索名称不起作用“语法不正确”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆