Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
listview C#按特定列排序_C#_Winforms_Sorting_Indexing - Fatal编程技术网

listview C#按特定列排序

listview C#按特定列排序,c#,winforms,sorting,indexing,C#,Winforms,Sorting,Indexing,如何在WinForms.NET 2.0中按特定列号对listview控件进行排序?e、 g.我有一个名为“行号”的列,其索引为1,我想在listview框中按该列升序对项目进行排序。我在许多Winform项目中使用过此列排序器: private void listView1_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e) { ListView myList

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

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

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

别弄明白为什么这件事被记下来了。为了快速分类,它非常有效!在asc/desc之间切换,这很容易做到!无论如何谢谢你!只需在您的项目中添加“using System.Collections;”,这很简单,而且很有效,对于基本ascend Sortse,请参阅Microsoft的此实现: