// Return a string representing this item's sub-item. private string ItemString(ListViewItem listview_item, int idx) { ListViewEx slvw = ( ListViewEx )listview_item.ListView; // Make sure the item has the needed sub-item. string value = ""; if (idx <= listview_item.SubItems.Count - 1) { value = listview_item.SubItems[idx].Text; } // Return the sub-item's value. if (slvw.Columns[idx].TextAlign == HorizontalAlignment.Right) { // Pad so numeric values sort properly. return(value.PadLeft(20)); } else { return(value); } }
// Compare two ListViewItems. public int Compare(object x, object y) { ListViewItem itemx = ( ListViewItem )(x); ListViewItem itemy = ( ListViewItem )(y); // Get the selected column index. ListViewEx slvw = ( ListViewEx )itemx.ListView; int idx = slvw.SelectedSortColumn; if (idx < 0) { return(0); } // Compare the items' strings. if (itemx.ListView.Sorting == SortOrder.Ascending) { return(String.Compare(ItemString(itemx, idx), ItemString(itemy, idx))); } else { return(-String.Compare(ItemString(itemx, idx), ItemString(itemy, idx))); } }
// Return a string representing this item as a // null-separated list of the item sub-item values. private string ItemString(ListViewItem listview_item) { ListViewEx slvw = ( ListViewEx )listview_item.ListView; // Make sure we have the sort sub-items' order. if (slvw._sortSubitems == null) { slvw.SetSortSubitems( ); } // Make an array to hold the sort sub-items' values. int num_cols = slvw.Columns.Count; string[] values = new string[num_cols]; // Build the list of fields in display order. for (int i = 0; i <= slvw._sortSubitems.Length - 1; i++) { int idx = slvw._sortSubitems[i]; // Get this sub-item's value. string item_value = ""; if (idx < listview_item.SubItems.Count) { item_value = listview_item.SubItems[idx].Text; } // Align appropriately. if (slvw.Columns[idx].TextAlign == HorizontalAlignment.Right) { // Pad so numeric values sort properly. values[i] = item_value.PadLeft(20); } else { values[i] = item_value; } } // Save the sub-item values in display order. for (int i = 0; i <= slvw._sortSubitems.Length - 1; i++) { int idx = slvw._sortSubitems[i]; // Make sure this item has this sub-item. if (idx < listview_item.SubItems.Count) { // Add the sub-item's value. if (slvw.Columns[idx].TextAlign == HorizontalAlignment.Right) { // Pad so numeric values sort properly. values[i] = listview_item.SubItems[idx].Text.PadLeft(20); } else { values[i] = listview_item.SubItems[idx].Text; } } } // Console.WriteLine(String.Join("|", values)); // Concatenate the values to build the result. return(String.Join("\0", values)); }