Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

listview C# sorting by specific column [duplicate]

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.

like image 368
rayanisran Avatar asked Nov 28 '11 03:11

rayanisran


2 Answers

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);
    }
 }
like image 65
Yaro Avatar answered Oct 21 '22 07:10

Yaro


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

like image 7
Hanlet Escaño Avatar answered Oct 21 '22 07:10

Hanlet Escaño