Bohn Bohn - 1 month ago 5
C# Question

Alphabetically Sorting the items on a ListView

I have a listview like this and in FormLoad event I should do some initializations for it such as this: ( I need these ) .

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


and the way I am adding items to it is pretty simple like this:

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


But I want them to be added and sorted alphabetically but when I add a new item to it and call Sort method, it doesn't do anything.
Why?! :(

EDIT: This is the whole section that at its last line I am calling Sort()
The goal is to have two list views, and a Move Button, when Move button is clicked the selected items from one listview should get moved to the other listview.
(Both listviews don't need to be sorted. Just the AvailLV listview should be sorted )

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

Answer

Where are you setting your ListView.Sorting Property

From above link:

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.


Looking at your edit, I think all you need to do is set the ListView.Sorting Property on AvailableLV and it will automatically sort your items as they are added. or instead of calling.

AvailableLV.Sort(); 

use

AvailableLV.Sorting = SortOrder.Ascending;