问题描述
我在一个名为 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# 搜索列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!