2011-11-28 88 views
5

如何在WinForms .NET 2.0中按特定列號對列表視圖控件進行排序?例如我有一個名爲「Line Number」的索引爲1的列,我想按升序對列表視圖中的項目進行排序。listview C#按特定列排序

+0

請參見本Microsoft實現:https://support.microsoft.com/en-us/kb/319401 – Mangesh

回答

6

我已經在很多的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

+0

就行了。謝謝。 – david

14

有例子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

不知道爲什麼這是下降標記。爲了快速排序它效果很好!在asc/desc之間進行切換很容易!不管怎麼說,還是要謝謝你! –

+0

只需添加「using System.Collections;」在你的項目上,這很簡單,它的工作原理是基本的升級 –