过滤在ListView项目 [英] Filtering items in a Listview

查看:115
本文介绍了过滤在ListView项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在的ListView 使用文本框筛选项目。结果
我已经成功地做​​一些东西,但它只能从我的列表视图删除项目,而不是把他们带回来。这里是我的code的一个小例子:

I am trying to filter items in a ListView by 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:

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 >:...

推荐答案

检查下面的示例应用程序

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

这篇关于过滤在ListView项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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