The Sorting property of a WinForms ListView only sorts by the first column, and only as text. To sort by whichever column the user clicks, assign your own IComparer to ListViewItemSorter and call Sort() from the ColumnClick event.
The tricky part is not the click handling but the comparison: sorted as text, “10” comes before “9” and “02/03/2024” sorts by day or month depending on culture. The comparer below sorts typed values when you provide them and falls back to text otherwise.
WinForms is Windows-only: target net8.0-windows with <UseWindowsForms>true</UseWindowsForms>.
The comparer
using System.Collections;
public sealed class ListViewColumnSorter : IComparer
{
public int Column { get; set; }
public SortOrder Order { get; set; } = SortOrder.Ascending;
public int Compare(object? x, object? y)
{
if (x is not ListViewItem a || y is not ListViewItem b)
return 0;
int result = CompareSubItems(GetSubItem(a), GetSubItem(b));
return Order == SortOrder.Descending ? -result : result;
}
private ListViewItem.ListViewSubItem? GetSubItem(ListViewItem item) =>
Column < item.SubItems.Count ? item.SubItems[Column] : null;
private static int CompareSubItems(ListViewItem.ListViewSubItem? a, ListViewItem.ListViewSubItem? b)
{
if (a is null)
return b is null ? 0 : -1;
if (b is null)
return 1;
// Typed values stored in Tag win over the display text.
if (a.Tag is IComparable valueA && b.Tag is not null && b.Tag.GetType() == valueA.GetType())
return valueA.CompareTo(b.Tag);
return string.Compare(a.Text, b.Text, StringComparison.CurrentCultureIgnoreCase);
}
}
Items with fewer subitems than the clicked column sort before the others instead of throwing ArgumentOutOfRangeException.
Wire it up in the form
public partial class MainForm : Form
{
private readonly ListViewColumnSorter sorter = new();
public MainForm()
{
InitializeComponent();
listView1.View = View.Details;
listView1.Columns.Add("Name", 150);
listView1.Columns.Add("Size", 100, HorizontalAlignment.Right);
listView1.Columns.Add("Modified", 150);
AddFile("report.pdf", 1_250_000, new DateTime(2024, 3, 2));
AddFile("notes.txt", 980, new DateTime(2023, 11, 15));
AddFile("photo.jpg", 3_400_000, new DateTime(2024, 1, 20));
listView1.ListViewItemSorter = sorter;
listView1.ColumnClick += ListView1_ColumnClick;
}
private void AddFile(string name, long size, DateTime modified)
{
var item = new ListViewItem(name);
item.SubItems.Add(new ListViewItem.ListViewSubItem(item, $"{size / 1024.0:N0} KB") { Tag = size });
item.SubItems.Add(new ListViewItem.ListViewSubItem(item, modified.ToShortDateString()) { Tag = modified });
listView1.Items.Add(item);
}
private void ListView1_ColumnClick(object? sender, ColumnClickEventArgs e)
{
if (e.Column == sorter.Column)
{
sorter.Order = sorter.Order == SortOrder.Ascending
? SortOrder.Descending
: SortOrder.Ascending;
}
else
{
sorter.Column = e.Column;
sorter.Order = SortOrder.Ascending;
}
listView1.Sort();
}
}
Clicking a column sorts by it; clicking it again reverses the order.
Why store values in Tag
The display text is formatted for people: “1,221 KB”, “3/2/2024”. Parsing it back is fragile. The original version of this example called DateTime.Parse inside Compare and caught the exception when the text was not a date. That is slow (the comparer runs thousands of times while sorting) and wrong as soon as the user’s culture differs from the one the text was formatted with.
Putting the real long or DateTime in the subitem’s Tag avoids both problems. The comparer only uses a Tag if both sides hold the same type, so a column with mixed or missing values still sorts consistently as text.
Note that item.SubItems[0] is the item’s own text; its Tag is separate from item.Tag. If you need typed sorting on the first column, set item.SubItems[0].Tag.
Practical notes
- Load before you assign the sorter. Setting
ListViewItemSortersorts the list immediately, and with a sorter in place the control keeps sorting as items are added. For large lists, add all items first (insideBeginUpdate/EndUpdate) and assign the sorter afterwards, as the example does. - Virtual mode. With
VirtualMode = true, the ListView does not own the items andSort()does nothing. Sort your own data list and callInvalidate(). - Sort indicator. The ListView header has no managed API for the up and down arrows. A simple workaround is to append ” ▲” or ” ▼” to the column’s
Textin the click handler. - Consider a DataGridView. If the data comes from a list of objects, a
DataGridViewbound to it supports column sorting with much less code.