我有一个这样的 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/