Author Topic: ListView IComparer with static topmost item  (Read 1432 times)

0 Members and 1 Guest are viewing this topic.

Keith™

  • Villiage Idiot
  • Seagull
  • Posts: 16899
  • Superior Stupidity at its best
ListView IComparer with static topmost item
« 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. }



Proud provider of opinion and arrogance since November 22, 2003 at 09:35:31 am
CadJockey Militia Field Marshal

Find me on https://parler.com @kblackie