C# 搜索列表框

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

问题描述

我在一个名为 listBox1 的列表框中有大量项目.我在顶部还有一个文本框(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

猫"

狗"

胡萝卜"

和花椰菜"

如果我开始输入字母 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# 搜索列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)