C#自动完成

cor*_*ews 43 c# autocomplete winforms

我正在尝试向文本框添加自动完成功能,结果来自数据库.它们的格式为

[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());
    }
}
Run Code Online (Sandbox Code Playgroud)

results是包含查询结果的数据集

查询是使用like语句的简单搜索查询.如果我们不使用自动完成并将结果抛入数组,则会返回正确的结果.

有什么建议?

编辑:

这是返回结果的查询

SELECT Name from view_customers where Details LIKE '{0}'
Run Code Online (Sandbox Code Playgroud)

{0}是搜索字符串的占位符.

Ste*_*rds 49

现有的自动完成功能仅支持按前缀搜索.似乎没有任何体面的方式来覆盖行为.

有些人通过覆盖OnTextChanged事件来实现自己的自动完成功能.这可能是你最好的选择.

例如,您可以在其ListBox下方添加一个TextBox,并将其默认可见性设置为false.然后您可以使用OnTextChanged事件TextBoxSelectedIndexChanged事件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;
}
Run Code Online (Sandbox Code Playgroud)

如果没有太多的努力,你可以做更多的事情:将文本附加到文本框,捕获其他键盘命令,等等.

  • 请记住,这意味着下拉列表不能覆盖窗口底部边缘下方的表格. (3认同)

Jim*_*ott 6

如果您决定使用基于用户输入的查询,请确保使用SqlParameters来避免SQL注入攻击

SqlCommand sqlCommand = new SqlCommand();
sqlCommand.CommandText = "SELECT Name from view_customers where Details LIKE '%" + @SearchParam + "%'";
sqlCommand.Parameters.AddWithValue("@SearchParam", searchParam);
Run Code Online (Sandbox Code Playgroud)