【发布时间】:2014-01-08 19:19:01
【问题描述】:
我正在使用 C#.net Windows 窗体,我需要创建一个搜索文本框来显示组合框值(类似于 google 搜索);组合框中显示的值将是 SQL 2005 数据库中的值(例如,用户正在搜索 FirstName,组合框将显示所有名字,当用户键入更多字母时,这些名字会被过滤……如果用户正在搜索姓氏,组合框显示数据库中的所有姓氏值..等)
当我在做上述任务时
我已经写了这样的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;
【问题讨论】:
-
编辑您的问题以显示将文本框的值插入 SQL 语句的整个代码片段。
-
在 cmd.excutereader() 语句中出现类似“必须声明标量变量”的错误
标签: c# sql-server