简体   繁体   中英

how to limit dropdown items in autocomplete textbox c#?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM