使用TextBox C#中的任何字符自动完成

时间:2016-08-15 09:10:25

标签: c# linq autocomplete

我想使用LINQ to entities将自动完成设置为文本框。

这是我的代码:

using (Reference_TraductionEntities context = new Reference_TraductionEntities())
{
    var source = new AutoCompleteStringCollection();

    var name = from a in context.Feuil1Prenom
               where a.PRENOMF.StartsWith("i")
               select a.PRENOMF;
    source.AddRange(name.ToArray());

    textBox1.AutoCompleteCustomSource = source;
    textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
    textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
}

此代码没问题,但只是字符“i”, 我希望自动完成文本框中的任何字符条目

我该如何解决?

谢谢,

2 个答案:

答案 0 :(得分:0)

试试这个

this.textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
this.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 >= 3)
    {
        //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;
     }
  }
}

答案 1 :(得分:0)

非常感谢BugFinder !!!!

我用" i"替换开头以textbox1.text ...

开头
using (Reference_TraductionEntities context = new Reference_TraductionEntities())
{
    var source = new AutoCompleteStringCollection();
    var name = from a in context.Feuil1Prenom
               where a.PRENOMF.StartsWith(textBox1.Text )
               select a.PRENOMF;
    source.AddRange(name.ToArray());

    textBox1.AutoCompleteCustomSource = source;
    textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
    textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
}

它有效!!!