/// <summary> /// Sorts the items in the list on the specified <paramref name="columnIndex" /> /// and draws a sort direction arrow to the column header. /// </summary> /// <param name="source">The source.</param> /// <param name="columnIndex">Index of the column.</param> /// <param name="comparer">The list item comparer used for the sorting.</param> public static void Sort(this ListView source, int columnIndex, IComparer comparer) { if (source == null) { return; } // Remove any existing direction arrows. if (columnIndex != -1) { source.Columns[columnIndex].Text = source.Columns[columnIndex].Text.TrimEnd(DescendingOrder, AscendingOrder); source.Columns[columnIndex].Text = source.Columns[columnIndex].Text.Trim(); } // Set the arrow characters to show the sort order if (source.Sorting == SortOrder.Ascending) { // Set the sort column to the new column. source.Sorting = SortOrder.Descending; source.Columns[columnIndex].Text = string.Format("{0} {1}", source.Columns[columnIndex].Text, AscendingOrder); } else { source.Sorting = SortOrder.Ascending; source.Columns[columnIndex].Text = string.Format("{0} {1}", source.Columns[columnIndex].Text, DescendingOrder); } // Set the ListViewItemSorter property to a new ListViewItemComparer object. source.ListViewItemSorter = comparer; // Call the sort method to manually sort. source.Sort(); // Resize the columns to fit the contents. source.AutoResizeAllColumns(); }