提问者:小点点

C#ListView搜索项不带清除列表


我有一个C#平台上的winform项目。我有listview和textbox,如下图所示。我想根据用户输入的文本值对列表重新排序。

我在这里询问之前研究过,我通常会看到基于删除和重新添加所有单元到listview的解决方案。我不想这样做,因为我的listview有太多带图片的项目,所以删除和重新添加项目会导致listview工作缓慢。

我想要的是,当用户在文本框中输入字符时,以这些字符开头的项目,将这些项目置于列表的顶部,类似于谷歌搜索系统。

我尝试了下面的代码,但这发送列表末尾的项目,即使我选择了索引0。谢谢。

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

共1个答案

匿名用户

ListView使用进行排序。Sort()函数,不确定默认行为是什么,但我认为您需要一个自定义比较器。

下面是(ab)使用ListViewItem实现的示例。标签

自定义比较器:

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

初始化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

当然,文本更改事件处理程序:

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

在搜索文本框中键入“是”,会将第2项和第4项排序在第1项和第3项前面。