【问题标题】:C# Textbox Search AutocompleteC# 文本框搜索自动完成
【发布时间】:2018-02-05 09:00:28
【问题描述】:

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

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,但不仅仅是ABABC。我该怎么做?谢谢!

【问题讨论】:

标签: c# search textbox


【解决方案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/

【讨论】:

  • 感谢您的回复。但是 SuggestString 是什么意思呢?
  • BurryLib 它实际上显示一个或多个建议的完成字符串。欲了解更多信息,您可以前往msdn.microsoft.com/en-us/library/…。希望你明白了。如果还没有得到。使用此链接..net-informations.com/q/faq/autocomplete.html。提醒我。如果你仍然没有得到。
  • 再次感谢。但它似乎不起作用。我从Here 读到,现有的自动完成功能只支持按前缀搜索,对吗?
  • 我认为,这完全取决于你想从哪里开始搜索..就像上面的例子一样,我提供了一些长度 ietText.Length >= 1。你也想要这样..是的,它正在搜索前缀方法。我以为这就是你想要的。BarryLib
  • 我想要的是当我输入目标字符串的子字符串时,例如BCABCDEF的文本框也可以显示可用的源代码。但是现在上面的代码只适用于ABABCABCD等。
猜你喜欢
  • 2012-03-20
  • 2018-07-29
  • 2017-10-22
  • 1970-01-01
  • 2013-08-20
  • 2021-07-09
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
相关资源
最近更新 更多