listview C#按特定列排序

时间:2011-11-28 03:57:58

标签: c# winforms sorting indexing

如何在WinForms .NET 2.0中按特定列号对listview控件进行排序?例如我有一个名为“行号”的列,其索引为1,我想按照升序对列表视图框中的项目进行排序。

2 个答案:

答案 0 :(得分:19)

MSDN上有一个例子ListView.ColumnClick article:非常简短。基本上,您编写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);
    }
 }

答案 1 :(得分:7)

我在许多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();
}

来源Click Here