如何限制自动完成文本框C#中的下拉项? [英] how to limit dropdown items in autocomplete textbox c#?

查看:94
本文介绍了如何限制自动完成文本框C#中的下拉项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有自动完成模式的文本框.当我输入前几个字符时,建议列表项超过15个. 我希望建议项目最多显示10个项目.

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.

我找不到财产来做.

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

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

推荐答案

您不能在AutoCompleteStringCollection类上使用LINQ.我建议您在TextBox的TextChanged事件中自行处理过滤.我在下面写了一些测试代码.输入一些文本后,我们将过滤并从Source()数据集中获取前10个匹配项.然后,我们可以为您的TextBox设置一个新的AutoCompleteCustomSource.我对其进行了测试,并且可行:

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

这篇关于如何限制自动完成文本框C#中的下拉项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆