Home > Enterprise >  C# ListView search item without clear list
C# ListView search item without clear list

Time:12-11

I have winform project on C# platform. I have listview and textbox as you see in pic below. I want to reorder the list according to the text value entered by the user.

I researched before ask here, I generally saw solutions based on removing and re-adding all units to listview again. I don't want to do that because my listview has too many items with pictures so removing and re-adding items causes listview to work slowly.

What I want is that, when the user enters characters in the textbox, the items which starts with this characters, bring this items the top of the list something similar google search system.

I tried the codes below but this send the item at the end of the list even though i chose index 0. Thanx.

enter image description here

private void txt_search_TextChanged(object sender, EventArgs e)
        {
            string text = txt_search.Text;
            var item = listView1.FindItemWithText(text);
            if (item != null)
            {
                int index = listView1.Items.IndexOf(item);

                if (index > 0)
                {
                    listView1.Items.RemoveAt(index);
                    listView1.Items.Insert(0, item);
                }
            }
        }

CodePudding user response:

ListView is sorted using the .Sort() function, not sure what the default behaviour is, but I think you need a custom comparer.

Here is an example implementation by (ab)using the ListViewItem.Tag.

Custom Comparer:

private class SearchCompare : Comparer<ListViewItem>
{
    public override int Compare([AllowNull] ListViewItem x, [AllowNull] ListViewItem y)
    {
        if (x?.Tag != null && y?.Tag != null)
        {
            return x.Tag.ToString().CompareTo(y.Tag.ToString());
        }
        return 0;
    }
}

Initializing the ListView:

var items = new[]
{
    "1 no",
    "2 yes",
    "3 no",
    "4 yes"
};
foreach (var item in items)
{
    listView1.Items.Add(item);
}
listView1.ListViewItemSorter = new SearchCompare(); // custom sorting

And ofcourse the text changed event handler:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    string text = textBox1.Text;
    foreach (ListViewItem item in listView1.Items)
    {
        if (item.Text.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) > -1)
        {
            item.Tag = "a"; // a is sorted before b
        }
        else
        {
            item.Tag = "b"; // b is sorted after a
        }
    }
    listView1.Sort();
}

Typing "yes" in the search textbox will sort items 2 and 4 in front of items 1 and 3.

  • Related