how to limit dropdown items in autocomplete textbox c#?

 ̄綄美尐妖づ 提交于 2019-12-13 07:09:32

问题


I have a textbox with autocomplete mode. When I enter first few characters, the suggestion list items exceeds more than 15. I want the suggestion items to show maximum of 10 items.

I don't find property to do it.

AutoCompleteStringCollection ac = new AutoCompleteStringCollection();
ac.AddRange(this.Source());

if (textBox1 != null)
{
    textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
    textBox1.AutoCompleteCustomSource = ac;
    textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
}

回答1:


You can't use LINQ on the AutoCompleteStringCollection class. I suggest you handle the filtering yourself in the TextChanged event of the TextBox. I have written some test code below. After entering some text, we will filter and take the top 10 matches from your Source() data set. Then we can set a new AutoCompleteCustomSource for your TextBox. I tested it and this works:

private List<string> Source()
{
    var testItems = new List<string>();
    for (int i = 1; i < 1000; i ++)
    {
        testItems.Add(i.ToString());
    }

    return testItems;
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    var topTenMatches = this.Source().Where(s => s.Contains(textBox1.Text)).Take(10);
    var autoCompleteSource = new AutoCompleteStringCollection();
    autoCompleteSource.AddRange(topTenMatches.ToArray());

    textBox1.AutoCompleteCustomSource = autoCompleteSource;
}


来源:https://stackoverflow.com/questions/35381891/how-to-limit-dropdown-items-in-autocomplete-textbox-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!