【问题标题】:How to retrieve records using textbox?如何使用文本框检索记录?
【发布时间】:2012-08-20 13:52:17
【问题描述】:

我正在尝试使用通配符查询在 gridview 中显示行,但它达不到标准...

protected void Button1_Click(object sender, EventArgs e)
{
    SqlCommand com = new SqlCommand("select * from Alphabates where Word 
                     like'"+TextBox1.Text+"'", new SqlConnection("data source=
                     USER\\SQLEXPRESS;initial catalog=vicky;integrated 
                     security=true"));

    try
    {
        com.Connection.Open();
        GridView1.DataSource = com.ExecuteReader();
        GridView1.DataBind();
        com.Connection.Close();
        com.Connection.Dispose();
    }
    catch (SqlException ex)
    {
        Label1.Text = ex.Message;
    }
}

【问题讨论】:

  • @pascal 我想要如果我输入 ab 所以它应该显示我的 Alphabates 数据库中的所有记录请帮助我

标签: c# asp.net sql sql-server sql-server-2005


【解决方案1】:

试试这个:

更改您的查询以在文本框值周围添加 %

通配符搜索需要一个 % 符号来获得所需的结果,否则它与使用等于 (=) 符号相同

"select * from Alphabates where Word like %'"+TextBox1.Text+"%'"

如果您想要以给定单词开头的行,则根据您的评论:

"select * from Alphabates where Word like '"+TextBox1.Text+"%'"

例如:

select * from Alphabates where Word like 'Some value'

相同
select * from Alphabates where Word ='Some value'

所以你应该把它改成

select * from Alphabates where Word like '%Some value%'

【讨论】:

  • 请检查引号..我已经更新了我的答案..请立即检查
  • 我想如果我在文本框中输入“ab”这样的单词,那么它应该显示所有以“aback”、“abase”、“abort”开头的单词...... ..
  • Select * from Alphabates where Word like '%"textbox1.text"%' it is another query .....
  • 伙计,我已经将您的答案评为有用............ Thanxxx Againnnnn...... .......
【解决方案2】:

请注意sql注入。

您应该在文本值周围添加 %,然后使用参数化 sql 来运行它,而不是使用字符串组合它。你会接受各种聪明的 sql。

看看这里的例子:

http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 2014-05-07
    • 2012-01-04
    • 1970-01-01
    相关资源
    最近更新 更多