How to sort a listview control by a specific column number in WinForms .NET 2.0? e.g. I have a column called "Line Number" whose index is 1, and I want to sort my items in the listview box by that in ascending order.
There is example on MSDN ListView.ColumnClick article: very short and simple. Essentially, you write a ListViewItemComparer
and use it each time you click a column:
class ListViewItemComparer : IComparer
{
private int col = 0;
public ListViewItemComparer(int column)
{
col = column;
}
public int Compare(object x, object y)
{
return String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
}
}
class MyForm : Form
{
// private System.Windows.Forms.ListView listView1;
// ColumnClick event handler.
private void ColumnClick(object o, ColumnClickEventArgs e)
{
this.listView1.ListViewItemSorter = new ListViewItemComparer(e.Column);
}
}
I have used this column sorter in many Winform Projects:
private void listView1_ColumnClick(object sender,
System.Windows.Forms.ColumnClickEventArgs e)
{
ListView myListView = (ListView)sender;
// Determine if clicked column is already the column that is being sorted.
if ( e.Column == lvwColumnSorter.SortColumn )
{
// Reverse the current sort direction for this column.
if (lvwColumnSorter.Order == SortOrder.Ascending)
{
lvwColumnSorter.Order = SortOrder.Descending;
}
else
{
lvwColumnSorter.Order = SortOrder.Ascending;
}
}
else
{
// Set the column number that is to be sorted; default to ascending.
lvwColumnSorter.SortColumn = e.Column;
lvwColumnSorter.Order = SortOrder.Ascending;
}
// Perform the sort with these new sort options.
myListView.Sort();
}
Source: Click Here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With