Posts tagged ‘listview’

ListView sort C#

If you need to sort using the ListView control it is straight forward. But what about leaving some of the rows out of the sort. For example if you need a total row in the end. Obviously you don’t want that last one as a part of the sort routine. Simply add to the ListViewItem.Tag a string something like DONT_SORT and look for that in the comparer.

public int Compare(object x, object y)
            int compareResult;
            ListViewItem listviewX, listviewY;

            // Cast the objects to be compared to ListViewItem objects
            listviewX = (ListViewItem)x;
            listviewY = (ListViewItem)y;

            // Don’t sort on requested tags
            if (listviewX.Tag.ToString().Equals(DONT_SORT))
                return compareResult = 1;
            if (listviewY.Tag.ToString().Equals(DONT_SORT)
                return compareResult = –1;