The other day I went looking for codes to sort listviews. Something quick and dirty. When I googled, I found many examples but all made my brain freeze. I just wanted a no frills bam-bam-1-2-3 codes. So for newbies out there or simply as a quick reference, here are the steps to sort listviews by their columns. Once you get the basics working, you can further tweak sorting logic at your leisure.
Step 1 – Declare a variable to hold the column index to sort by
// This field is used by the IComparer.Compare method.
private int _ColumnToSortBy;
Step 2 – Have the form implement IComparer.Compare interface
// ListView will call this whenever items need to be sorted.
int IComparer.Compare(object x, object y)
{
var xString = (x as ListViewItem).SubItems[_ColumnToSortBy].Text;
var yString = (y as ListViewItem).SubItems[_ColumnToSortBy].Text;
return string.Compare(xString, yString);
}
Step 3 – Set the ListView.ListViewItemSorter property in form constructor
// Property accepts any object that implement IComparer.Compare interface.
_ListView.ListViewItemSorter = this;
Step 4 – Call ListView.Sort() in the ListView.ColumnClick event handler.
// Save the index of the just clicked column and call ListView.Sort().
void ListView_ColumnClick(object sender, ColumnClickEventArgs e)
{
_ColumnToSortBy = e.Column;
_ListView.Sort();
}
Complete Sample Form
Just to be complete, here are codes for a sample listview sorting form.
using System.Collections;
using System.Windows.Forms;
class SampleForm : Form, IComparer
{
ListView _ListView;
int _ColumnToSortBy;
public SampleForm() {
// Initialize form.
InitializeForm();
// Set the item sorter property.
_ListView.ListViewItemSorter = this;
// Subscribe to column click events.
_ListView.ColumnClick += new ColumnClickEventHandler(ListView_ColumnClick);
}
int IComparer.Compare(object x, object y) {
var xString = (x as ListViewItem).SubItems[_ColumnToSortBy].Text;
var yString = (y as ListViewItem).SubItems[_ColumnToSortBy].Text;
return string.Compare(xString, yString);
}
void ListView_ColumnClick(object sender, ColumnClickEventArgs e) {
_ColumnToSortBy = e.Column;
_ListView.Sort();
}
void InitializeForm() {
// ListView.
_ListView = new ListView();
_ListView.Dock = DockStyle.Fill;
_ListView.Location = new System.Drawing.Point(0, 0);
_ListView.View = View.Details;
// Add 2 listview columns.
_ListView.Columns.Add(“Column One”, 125);
_ListView.Columns.Add(“Column Two”, 125);
// Add 3 listview items.
_ListView.Items.Add(“Listview item #1”);
_ListView.Items.Add(“Listview item #2”);
_ListView.Items.Add(“Listview item #3”);
_ListView.Items[0].SubItems.Add(“Listview item #C”);
_ListView.Items[1].SubItems.Add(“Listview item #B”);
_ListView.Items[2].SubItems.Add(“Listview item #A”);
// SampleForm.
this.ClientSize = new System.Drawing.Size(300, 300);
this.Controls.Add(_ListView);
this.StartPosition = FormStartPosition.CenterScreen;
}
}