The ListView control provides a Sort method that orders items alphabetically based on the text in the first column. If you want to sort based on other column values or order items in any other way, you need to create a custom implementation of the IComparer interface that can perform the work.
The IComparer interface defines a single method named Compare, which takes two objects and determines which one should be ordered first. Here is a custom ListViewItemComparer class that implements IComparer. It provides two additional properties: Column and Numeric. Column indicates the column that should be used for sorting, and Numeric is a Boolean flag that can be set to true if you want to perform number-based comparisons instead of alphabetic comparisons.
using System; using System.Collections; using System.Windows.Forms; public class ListViewItemComparer : IComparer { private int column; private bool numeric = false; public int Column { get {return column;} set {column = value;} } public bool Numeric { get {return numeric;} set {numeric = value;} } public ListViewItemComparer(int columnIndex) { Column = columnIndex; } public int Compare(object x, object y) { ListViewItem listX = (ListViewItem)x; ListViewItem listY = (ListViewItem)y; if (Numeric) { // Convert column text to numbers before comparing. // If the conversion fails, just use the value 0. decimal listXVal, listYVal; try { listXVal = Decimal.Parse(listX.SubItems[Column].Text); } catch { listXVal = 0; } try { listYVal = Decimal.Parse(listY.SubItems[Column].Text); } catch { listYVal = 0; } return Decimal.Compare(listXVal, listYVal); } else { // Keep the column text in its native string format // and perform an alphabetic comparison. string listXText = listX.SubItems[Column].Text; string listYText = listY.SubItems[Column].Text; return String.Compare(listXText, listYText); } } }
Now to sort the list view, you simply need to create a ListViewItemComparer instance, configure it appropriately, and then set it in the ListView.ListViewItemSorter property before you call the ListView.Sort method.
The following form demonstrates a simple test of the ListViewItemComparer. Every time the user clicks a column header in the list view, a new ListViewItemComparer is created and used to sort the list based on the clicked column.
using System; using System.Windows.Forms; public class ListViewItemSort : System.Windows.Forms.Form { // (Designer code omitted.) private void ListView1_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e) { ListViewItemComparer sorter = new ListViewItemComparer(e.Column); ListView1.ListViewItemSorter = sorter; ListView1.Sort(); } }
The listview c# sorting is able to be performed in all views in the control
ReplyDelete