Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 432
Yuki Kutsuya Avatar asked May 14 '13 18:05

Yuki Kutsuya


People also ask

How do I filter in C#?

C# filter list with iteration. In the first example, we use a foreach loop to filter a list. var words = new List<string> { "sky", "rock", "forest", "new", "falcon", "jewelry" }; var filtered = new List<string>(); foreach (var word in words) { if (word. Length == 3) { filtered.


2 Answers

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; }
}
like image 199
Damith Avatar answered Sep 30 '22 04:09

Damith


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.

like image 22
Rodrigo Avatar answered Sep 30 '22 05:09

Rodrigo