【问题标题】:C# ListView search item without clear listC# ListView 搜索项没有明确的列表
【发布时间】:2022-01-15 04:52:05
【问题描述】:

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

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

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

我尝试了下面的代码,但即使我选择了索引 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);
                }
            }
        }

【问题讨论】:

  • 考虑在虚拟模式中使用 ListView,以便在要显示大列表时获得更好的性能。由于您可以控制正在显示的数据,因此您将能够执行更好的过滤/排序例程。
  • @Fixations 答案对我有用。感谢您的关注。

标签: c# sorting listview search


【解决方案1】:

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 的前面。

【讨论】:

  • 首先,感谢您的关注和您的时间。它有效,但我删除了 [AllowNull]。因为应用程序无法定义它。如果我这样做,它会在未来引起问题吗? (见图)link
  • 那些是用于代码分析目的的自定义注释,我什至不再注意到它们了。我编辑了问题并删除了这些问题。
猜你喜欢
  • 1970-01-01
  • 2014-05-11
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多