how to limit dropdown items in autocomplete textbo

2019-09-02 19:45发布

问题:

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;
}