C#搜索一个listBox

3

我有一个名为listBox1的列表框中有大量项目,顶部还有一个textBox(textBox1)。 我希望能够在textBox中输入内容,然后listBox搜索其项并找到包含我所输入内容的项。

例如,假设listBox包含:

"Cat"

"Dog"

"Carrot"

和"Brocolli"

如果我开始输入字母C,那么我希望它显示Cat和Carrot,在我键入a时,它应该继续显示它们两个,但是当我添加r时,它应该从列表中移除Cat。有没有办法做到这一点?


1
你正在使用什么GUI框架?Winforms?WPF?还是其他的框架?TextBoxListBox并不是纯C#的一部分... - stakx - no longer contributing
WinForms,抱歉我应该先说明一下。 - Luke Berry
5个回答

6

筛选列表框。试试这个:

    List<string> items = new List<string>();
    private void Form1_Load(object sender, EventArgs e)
    {
        items.AddRange(new string[] {"Cat", "Dog", "Carrots", "Brocolli"});

        foreach (string str in items) 
        {
            listBox1.Items.Add(str); 
        }
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        listBox1.Items.Clear();

        foreach (string str in items) 
        {
            if (str.StartsWith(textBox1.Text, StringComparison.CurrentCultureIgnoreCase))
            {
                listBox1.Items.Add(str);
            }
        }
    }

如果您不打算使用AddRange,那么应该使用BeginUpdate/EndUpdate来禁止不必要的绘制。 - Aaron McIver
我非常喜欢这个。谢谢! - Luke Berry

2

-1 虽然类似,但是这是一个带有文本框的列表框;假设 OP 想要实现类似于“按键过滤”行为,就像 ICollectionView.Filter。 - Aaron McIver

1

这只是一个基本的例子,但它应该能帮助你入门...

    public partial class Form1 : Form
    {
        List<String> _animals = new List<String> { "cat", "carrot", "dog", "goat", "pig" };

        public Form1()
        {
            InitializeComponent();

            listBox1.Items.AddRange(_animals.ToArray());
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            String search = textBox1.Text;

            if (String.IsNullOrEmpty(search))
            {
                listBox1.Items.Clear();
                listBox1.Items.AddRange(_animals.ToArray());
            }

            var items = (from a in _animals
                        where a.StartsWith(search)
                        select a).ToArray<String>();

            listBox1.Items.Clear();
            listBox1.Items.AddRange(items);
        } 
    }

如果列表很长,清除和添加范围会影响性能吗?或者因为它们都是引用,所以不重要? - Ziv
在某个时候,基于列表大小会有性能损失;但是,在性能受到影响之前,您可以扩展到相当大的规模。 - Aaron McIver
你知道合适的大小是多少吗?或者大概在哪里?我希望列表中至少有几百个项目。 - Luke Berry
@LukeBerry 你只需要几百就可以搞定。 - Aaron McIver

1
为了得到被询问者期望的结果,您需要使用Contains方法而不是StartWith方法。像这样:
private void textBox1_TextChanged(object sender, EventArgs e)
    {
        listBox1.Items.Clear();

        foreach (string str in items)
        {
            if (str.ToUpper().Contains(textBox1.Text.ToUpper()))
            {
                listBox1.Items.Add(str);
            }
        }
    }

我正在寻找这个。

0

我认为你需要使用linq查询,然后将结果绑定到数据。在WPF中的一个例子是这里,但我相信你也可以在winforms中做同样的事情。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接