文本框搜索类似于谷歌



我使用的是C#.net Windows窗体,我需要创建一个显示组合框值的搜索文本框(类似于谷歌搜索);组合框中显示的值将是SQL 2005数据库中的值(例如,用户在FirstName上搜索,组合框将显示所有名字,这些名字会随着用户键入更多字母而被过滤……如果用户在LastName上搜索时,组合框会显示数据库中的所有LastName值。等等)

当我在做上述任务

我已经编写了类似的sql查询

SELECT  distinct(person_Firstname+''+person_Lastname) 
AS 
name FROM persondetails 
WHERE name Like '%'+@name+'%'

当我执行这个查询时,它会给出这样的错误——必须声明一个标量可变

我的目标是,当我在文本框中输入第一个字母时,它会显示所有以该字母开头的名字,就像在谷歌中一样。。。

有人能纠正这个吗。。。。

private void tbautocomplete_TextChanged(object sender, EventArgs e)
{
    AutoCompleteStringCollection namecollection = new AutoCompleteStringCollection();
    SqlConnection con = new SqlConnection(@"Data Source=88888;Initial Catalog=contrynames;Integrated Security=True");
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT  distinct(person_Firstname+''+person_Lastname) AS name FROM persondetails WHERE name Like '%'+@name+'%'";
    con.Open();
    SqlDataReader rea = cmd.ExecuteReader();
    if (rea.HasRows == true)
    {
        while (rea.Read())
        namecollection.Add(rea["name"].ToString());            
    }
    rea.Close();
    tbautocomplete.AutoCompleteMode = AutoCompleteMode.Suggest;
    tbautocomplete.AutoCompleteSource = AutoCompleteSource.CustomSource;
    tbautocomplete.AutoCompleteCustomSource = namecollection;

听起来你正试图在应用程序中构建自动完成功能。您只是缺少SqlCommand上的参数。试试这个:

string searchFor = "%" + txtName.Text + "%"; //the string the user entered.
cmd.CommandText = @"SELECT  distinct(person_Firstname+''+person_Lastname) AS name
                    FROM persondetails 
                    WHERE person_Lastname Like @name
                    OR person_Firstname LIKE @name";
cmd.Parameters.AddWithValue("@name", searchFor);

WHERE子句必须使用表中的列名。听起来好像您想将名字或姓氏列与搜索令牌相匹配。

 WHERE person_Lastname LIKE @name
    OR person_Firstname LIKE @name

您要查找的功能称为自动完成。我不熟悉Windows窗体中的自动完成控件,但如果没有内置控件,肯定会有第三方控件来执行此操作。

AutoComplete控件可能会提供一个事件回调,您可以在其中放置SQL查询以提供可能的完成。

至于您的SQL错误,它看起来可能是列名的问题,但如果没有您的模式,很难判断。

编辑:

我看到你已经在使用自动完成控件了。SQL中的问题是查询中有@name参数,但您还没有将该参数添加到cmd对象中,因此它不知道该在其中放置什么值。

最新更新