TheSwamp

Code Red => .NET => Topic started by: Keith™ on August 23, 2018, 11:56:16 PM

Title: ListView IComparer with static topmost item
Post by: Keith™ on August 23, 2018, 11:56:16 PM
I've been playing with a sorter for layout tab names in a ListView. The problem I wanted to solve was I needed the Model tab to always be the first item in the list. To that end, I've built this IComparer to do the job. It only works correctly if you are sorting on a single column. Sorting on multiple columns produce unreliable results, but since I'm only using a single column, its of no consequence for me.

Code - C#: [Select]
  1. public class ListViewItemComparer : System.Collections.IComparer
  2. {
  3.     private int col;
  4.     private SortOrder sort;
  5.  
  6.     public ListViewItemComparer()
  7.     {
  8.         col = 0;
  9.         sort = SortOrder.Ascending;
  10.     }
  11.  
  12.     public ListViewItemComparer(int column, SortOrder order)
  13.     {
  14.         col = column;
  15.         sort = order;
  16.     }
  17.  
  18.     public int Compare(object x, object y)
  19.     {
  20.         string left = ((ListViewItem)x)[col].Text;
  21.         string right = ((ListViewItem)y)[col].Text;
  22.         if (lvx.SubItems[col].Text == "Model")
  23.         {
  24.             return -1;
  25.         }
  26.         else if (lvy.SubItems[col].Text == "Model")
  27.         {
  28.             return 1;
  29.         }
  30.         else
  31.         {
  32.             return (sort == SortOrder.Descending) ? (right.CompareTo(left)) : (left.CompareTo(right));
  33.         }
  34.     }
  35. }