C#自动完成我正在尝试向文本框添加自动完成功能,结果来自数据库。它们的格式为[001]最后,第一中间目前,您必须输入[001] ...才能显示要显示的条目。所以问题是我希望它完成,即使我先键入firstname。所以,如果一个条目是[001] Smith,John D.如果我开始输入John,则此条目应显示在自动完成的结果中。目前代码看起来像AutoCompleteStringCollection acsc = new AutoCompleteStringCollection();txtBox1.AutoCompleteCustomSource = acsc;txtBox1.AutoCompleteMode = AutoCompleteMode.Suggest; txtBox1.AutoCompleteSource = AutoCompleteSource.CustomSource; ....if (results.Rows.Count > 0)
for (int i = 0; i < results.Rows.Count && i < 10; i++)
{
row = results.Rows[i];
acsc.Add(row["Details"].ToString());
}}results是包含查询结果的数据集查询是使用like语句的简单搜索查询。如果我们不使用自动完成并将结果抛入数组,则会返回正确的结果。有什么建议?编辑:这是返回结果的查询SELECT Name from view_customers where Details LIKE '{0}'{0}是搜索字符串的占位符。
3 回答
潇潇雨雨
TA贡献1833条经验 获得超4个赞
现有的自动完成功能仅支持按前缀搜索。似乎没有任何体面的方式来覆盖行为。
有些人通过覆盖OnTextChanged事件来实现自己的自动完成功能。这可能是你最好的选择。
例如,您可以在其ListBox下方添加一个TextBox,并将其默认可见性设置为false。然后您可以使用OnTextChanged事件TextBox和SelectedIndexChanged事件ListBox来显示和选择项目。
这似乎是一个很好的例子:
public Form1(){
InitializeComponent();
acsc = new AutoCompleteStringCollection();
textBox1.AutoCompleteCustomSource = acsc;
textBox1.AutoCompleteMode = AutoCompleteMode.None;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;}private void button1_Click(object sender, EventArgs e){
acsc.Add("[001] some kind of item");
acsc.Add("[002] some other item");
acsc.Add("[003] an orange");
acsc.Add("[004] i like pickles");}void textBox1_TextChanged(object sender, System.EventArgs e){
listBox1.Items.Clear();
if (textBox1.Text.Length == 0)
{
hideResults();
return;
}
foreach (String s in textBox1.AutoCompleteCustomSource)
{
if (s.Contains(textBox1.Text))
{
Console.WriteLine("Found text in: " + s);
listBox1.Items.Add(s);
listBox1.Visible = true;
}
}}void listBox1_SelectedIndexChanged(object sender, System.EventArgs e){
textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString();
hideResults();}void listBox1_LostFocus(object sender, System.EventArgs e){
hideResults();}void hideResults(){
listBox1.Visible = false;}如果没有太多努力,您可以做更多的事情:将文本附加到文本框,捕获其他键盘命令,等等。
波斯汪
TA贡献1811条经验 获得超4个赞
如果您决定使用基于用户输入的查询,请确保使用SqlParameters来避免SQL注入攻击
SqlCommand sqlCommand = new SqlCommand();sqlCommand.CommandText = "SELECT Name from view_customers where Details LIKE '%" + @SearchParam + "%'";sqlCommand.Parameters.AddWithValue("@SearchParam", searchParam);- 3 回答
- 0 关注
- 531 浏览
添加回答
举报
0/150
提交
取消
