using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Windows.Forms; namespace ConvertPTU { 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) { // Chuyển text thành số trước khi so sánh. // Nếu chuyển đổi thất bại, sử dụng giá trị 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 { // Giữ nguyên text ở định dạng chuỗi // và thực hiện so sánh theo thứ tự alphabetic. string listXText = listX.SubItems[Column].Text; string listYText = listY.SubItems[Column].Text; return String.Compare(listXText, listYText); } } } }
private void listView_ListSite_ColumnClick(object sender, ColumnClickEventArgs e) { ListViewItemComparer sorter = new ListViewItemComparer(e.Column); listView_ListSite.ListViewItemSorter = sorter; listView_ListSite.Sort(); }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)