listview c#按特定列排序

本文关键字:排序 listview | 更新日期: 2023-09-27 18:16:00

如何在WinForms .NET 2.0中按特定列数排序listview控件?例:我有一个名为"Line Number"的列,其索引为1,我想按升序对listview框中的项目进行排序。

listview c#按特定列排序

在MSDN ListView上有一个例子。ColumnClick文章:非常简短和简单。实际上,您编写一个ListViewItemComparer,并在每次单击列时使用它:

 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);
    }
 }

我已经在许多Winform项目中使用了这个列排序器:

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();
}

来源:点击这里