C# 过滤列表视图中的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16549823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filtering items in a Listview
提问by Yuki Kutsuya
I am trying to filter items in a ListViewby using a TextBox.
I've managed to make something, but it can only delete items from my listview, not bring them back. Here is a little example of my code:
我正在尝试ListView使用TextBox.
我已经设法制作了一些东西,但它只能从我的列表视图中删除项目,而不能将它们带回来。这是我的代码的一个小例子:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string value = textBox1.Text.ToLower();
for (int i = listView1.Items.Count - 1; -1 < i; i--)
{
if
(listView1.Items[i].Text.ToLower().StartsWith(value) == false)
{
listView1.Items[i].Remove();
}
}
}
Does anybody has an idea on how to retrieve the deleted items? I can't seem to figure it out >:...
有没有人知道如何检索已删除的项目?我似乎无法弄清楚>:...
采纳答案by Damith
check below sample app
检查下面的示例应用程序
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
public partial class Form1 : Form
{
// keep list of listview items
List<Data> Items = new List<Data>();
public Form1()
{
InitializeComponent();
// get initial data
Items = new List<Data>(){
new Data(){ Id =1, Name ="A"},
new Data(){ Id =2, Name ="B"},
new Data(){ Id =3, Name ="C"}
};
// adding initial data
listView1.Items.AddRange(Items.Select(c => new ListViewItem(c.Name)).ToArray());
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
listView1.Items.Clear(); // clear list items before adding
// filter the items match with search key and add result to list view
listView1.Items.AddRange(Items.Where(i=>string.IsNullOrEmpty(textBox1.Text)||i.Name.StartsWith(textBox1.Text))
.Select(c => new ListViewItem(c.Name)).ToArray());
}
}
class Data
{
public int Id { get; set; }
public string Name { get; set; }
}
回答by AAlferez
回答by Rodrigo
You can change your logic and first search the items to delete, them delete they.
您可以更改逻辑并首先搜索要删除的项目,然后删除它们。
IList<Object> itemsToDelete = new List<Object>( listView1.find(delegate(string text){
return !text.ToLower().StartsWith(value);
}));
listView1.Remove(itemsToDelete);
return itemsToDelete;
But you have to return another list. When you delete the items form the original list, you cant recovery It. You have to store it in another list.
但是你必须返回另一个列表。当您从原始列表中删除项目时,您将无法恢复它。您必须将其存储在另一个列表中。

