c# - 按字母顺序对 ListView 上的项目进行排序

标签 c# winforms

我有一个这样的 ListView ,在 FormLoad 事件中我应该为它做一些初始化,例如:(我需要这些)。

    listView.Scrollable = true;
    listView.HideSelection = false;
    listView.FullRowSelect = true;
    listView.View = View.Details;
    listView.HeaderStyle = ColumnHeaderStyle.None;
    ColumnHeader header = new ColumnHeader();
    header.Text = "MyHdr";
    header.Name = "MyCol";
    header.Width = listView.ClientSize.Width;
    listView.Columns.Add(header);

我向其中添加项目的方式非常简单,如下所示:

listView.Items.Add("hello");
listView.Items.Add("How are you");
//... etc

但我希望它们按字母顺序添加和排序,但是当我向其中添加一个新项目并调用 Sort 方法时,它什么也没做。 为什么?! :(

编辑:这是我在最后一行调用 Sort() 的整个部分 目标是有两个 ListView 和一个移动按钮,当单击移动按钮时,一个 ListView 中的选定项目应该移动到另一个 ListView 。 (两个 ListView 都不需要排序。只需要对 AvailLV ListView 进行排序)

private void MoveBtn_Click(object sender, EventArgs e)
{
    ListView source=null;
    ListView target= null;

    if(AvailableLV.SelectedItems.Count>0)
    {
        source = AvailableLV;
        target = SelectedLV;
    }

    if(SelectedLV.SelectedItems.Count>0)
    {
        source = SelectedLV;
        target = AvailableLV;
    }

    if (source != null && target != null)
    {
        HaulItems(source, target);
    }
}

private void HaulItems(ListView source , ListView target)
{
    foreach(ListViewItem item in source.Items)
    {
        if(item.Selected)
        {
            source.Items.Remove(item);
            target.Items.Add(item);
        }
    }
    AvailableLV.Sort();
}

最佳答案

你在哪里设置你的ListView.Sorting Property

来自上面的链接:

The Sorting property allows you to specify whether or not items are sorted in the ListView control. By default, no sorting is performed. When the Sorting property is set to Ascending or Descending, the items in the ListView are sorted automatically in ascending alphabetical order (when the property is set to Ascending) or descending alphabetical order (when the property is set to Descending). You can use this property to automatically sort items that are displayed in your ListView control to make it easier for users to find items when a large number of items are available.


查看您的编辑,我认为您需要做的就是在 AvailableLV 上设置 ListView.Sorting 属性,它会在添加项目时自动对它们进行排序。或者不打电话。

AvailableLV.Sort(); 

使用

AvailableLV.Sorting = SortOrder.Ascending;

关于c# - 按字母顺序对 ListView 上的项目进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10779031/

相关文章:

c# - 如何从纯文本中检索粗体、斜体和带下划线的单词并用 HTML 标记包围它们

c# - 在 .NET Core 中以字符串形式返回 View

c# - 提取 IEnumerable<T> 中其键值等于 IEnumerable<U> 中的键值之一的项目

c# - 如何从 BackgroundWorker 返回列表以供 UI 线程中的下一行代码使用?

c# - 尝试在 Winform 应用程序中显示大 (2 GB) Tiff 图像的一部分

c# - ef core 在更新数据库期间不使用 ASPNETCORE_ENVIRONMENT

c# - 为什么即使我将 Expires 设置为 null,JWT 也会包含 EXP 声明?

c# - 在不同机器上运行 .NET 应用程序

c# - 无法调整已更改图像的大小? C# 窗体

vb.net - vb.net中的表单的自定义构造函数: Best practices