How to: Sort ListView Items

How to: Sort ListView Items
http://msdn.microsoft.com/en-us/library/ms229643(VS.80).aspx

class ListViewItemComparer : IComparer
{
    private int column;
    public ListViewItemComparer() : this(0) {}
    public ListViewItemComparer(int column)
    {
        this.column = column;
    }
    public int Compare(object x, object y)
    {
        return String.Compare(((ListViewItem)x).SubItems[column].Text,
                                        ((ListViewItem)y).SubItems[column].Text);
    }
}

/////
public partial class Form1 : Form
{
[…]
      private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
      {
            // Set the column number that is to be sorted; default to ascending.
            this.listView1.ListViewItemSorter = new ListViewItemComparer(e.Column);
            // Perform the sort with these new sort options.
            this.listView1.Sort();
        }
}

Leave a Reply

Your email address will not be published. Required fields are marked *