C#文本框搜索自动完成

时间:2017-08-28 06:43:54

标签: c# search textbox

我有一个文本框,用于键入字符串并显示此文本框中的所有可用结果。当前代码如下:

private void Form_Load(object sender, EventArgs e)
{
    TextBox.AutoCompleteMode = AutoCompleteMode.Suggest;
    TextBox.AutoCompleteSource = AutoCompeteSource.CustomSource;
}

private void TextBox_TextChanged(object sender, EventArgs e)
{
    TextBox t = sender as TextBox;
    if(t != null)
    {
        if(t.Text.Length > = 1)
        {
            AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
            collection.AddRange(s.Name);
            this.TextBox.AutoCompleteCustomSource = collection;
        }
    }
}

在上面的代码中,s.Name是我要搜索的所有字符串的来源。它只能正确键入字符串的第一个字母。例如。其中一个s.Name可能是ABCDEF当我输入任何子字符串时,我希望它可用,可能是EFBC,但不仅仅是AB或{ {1}}。我该怎么做?谢谢!

1 个答案:

答案 0 :(得分:1)

我不会帮助您提供所有代码,以便您可以复制或粘贴。所以我要提出一个想法.. 查看AutoCompleteSource,AutoCompleteCustomSource和AutoCompleteMode属性。

textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        TextBox t = sender as TextBox;
        if (t != null)
        {
            //say you want to do a search when user types 3 or more chars
            if (t.Text.Length >= 1)
            {
                //SuggestStrings will have the logic to return array of strings either from cache/db
                string[] arr = SuggestStrings(t.Text);

                AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
                collection.AddRange(arr);

                this.textBox1.AutoCompleteCustomSource = collection;
            }
        }
    }

希望它有所帮助。如果你还没有理解,请通知我。 有关更多信息,您可以喜欢这篇文章...... http://www.c-sharpcorner.com/article/autocomplete-textbox-in-C-Sharp/