C#搜索列表框 [英] C# Searching a listBox

查看:126
本文介绍了C#搜索列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在名为listBox1的listBox中有大量项目.我在顶部也有一个textBox(textBox1).我希望能够在textBox中键入内容,并且listBox可以搜索该项目的内容,并找到包含我所键入内容的内容.

I have a large amount of items in a listBox called listBox1. I also have a textBox (textBox1) at the top. I want to be able to type into the textBox and the listBox searches through it's item's and finds ones that contain what I am typing.

例如,说listBox包含

For example, say the listBox contains

猫"

狗"

胡萝卜"

和"Brocolli"

and "Brocolli"

如果我开始输入字母C,那么我希望它同时显示Cat和Carrot,当我输入a时,它应该继续显示它们,但是当我添加r时,它应该从列表中删除Cat.反正有这样做吗?

If I start typing the letter C, then I want it to show both Cat and Carrot, when I type a it should keep showing them both, but when I add an r it should remove Cat from the list. Is there anyway to do this?

推荐答案

过滤列表框.试试这个:

Filter the listbox. Try this:

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

这篇关于C#搜索列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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