C# ListView 搜索项目没有清晰的列表

标签 c# sorting listview search

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

我在提问之前进行了研究,我通常看到的解决方案是基于删除所有单元并将其重新添加到 ListView 。我不想这样做,因为我的 ListView 有太多带有图片的项目,因此删除和重新添加项目会导致 ListView 运行缓慢。

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

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

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

最佳答案

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

下面是使用 ListViewItem.Tag 实现的示例。

自定义比较器:

private class SearchCompare : Comparer<ListViewItem>
{
    public override int Compare(ListViewItem x, 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();
}

在搜索文本框中键入“yes”会将项目 2 和 4 排序在项目 1 和 3 之前。

关于C# ListView 搜索项目没有清晰的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70305474/

相关文章:

c# - 查询名称中有空格的表

android - 访问更新 ListView 的第一个元素会导致 System.ArgumentOutOfRangeException

c# - 更少锁定的线程安全

c# - 对 Object[] 数组列表的 LINQ 查询

c# - 带有混合触发器的 ListView 奇怪行为

android - 可扩展的 ListView 按年/月对项目进行分组

android - 在 ListView 中查找点击的行并获取数据

MySql 排序 varchar as int,以字符开头

java - 在数字字段上排序 db4o Android

javascript - 将相关元素嵌套在一起父/子