Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

c# - Filtering items in a Listview

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...