When you use Resource Explorer to view a file, you can sort the file by its name, size, type, and different date columns. NET provides a ListView component that does not directly provide such functionality, but is not difficult to implement.
The function of the Listview.sort () method is to "sort items in a list view", but nothing happens when you call it because you do not specify a sequencer for Listview1.listviewitemsorter. So, first you have to write a sort class.
public class Mysorter:icomparer
{
Private comparer comparer;
private int sortcolumn;
Private SortOrder SortOrder;
Public Mysorter ()
{
sortcolumn=0;
Sortorder=sortorder.none;
Comparer=comparer.default;
}
Specify the column to sort
public int SortColumn
{
get {return sortcolumn;}
set {Sortcolumn=value;}
}
Specify sort by ascending or descending order
Public SortOrder SortOrder
{
get {return sortOrder;}
set {Sortorder=value;}
}
public int Compare (Object X,object y)
{
int compareresult;
ListViewItem itemx= (ListViewItem) x;
ListViewItem itemy= (ListViewItem) y;
Here you are able to provide your own defined sort
Compareresult=comparer.compare (Itemx.subitems[this.sortcolumn]. Text,itemy.subitems[this.sortcolumn]. Text);
if (this. sortorder==sortorder.ascending)
return compareresult;
Else
if (this. sortorder==sortorder.descending)
return (-compareresult);
Else
return 0;
}
}
How to use this class is very easy. Create a new Windows application, add the ListView component ListView1, and set its View property to details.
Add Sort Class
Private Mysorter Sorter;
changing window constructors
Public Form1 ()
{
InitializeComponent ();
Sorter=new Mycolumnsorter ();
Specifying sort classes for Listviewitemsorter
This.listview1.listviewitemsorter=sorter;
Sorter. sortorder=sortorder.ascending;
}
Add code to click Header Events
private void Listview1_columnclick (object sender, System.Windows.Forms.ColumnClickEventArgs e)
{
if (E.column==this.sorter.sortcolumn)
{
if (this.sorter.sortorder==sortorder.ascending)
this.sorter.sortorder=sortorder.descending;
Else
if (this.sorter.sortorder==sortorder.descending)
this.sorter.sortorder=sortorder.ascending;
Else
Return
}
Else
{
This.sorter.sortcolumn=e.column;
}
This.listView1.Sort ();
}
Assuming you need to define the sort yourself, you can change the compare () method of the sequencer.
Transfer from Domanager
How to sort items in a ListView