ListView 排序问题

 

DataGrid  中有自带的排序,但是在 ListeView 中却没有这一项,下面就给出我平时用的 ListView 的排序使用方法,给志同道合的朋友们参考参考:
ColumnClick 事件下添加:
其中要注意: int sortColumn=-1; 其中 sortColumn 用来记录上次排序的列的索引
private void listView1_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
         {
              if(this.listView1.SelectedItems.Count!=0)
                   this.listView1.SelectedItems.Clear();
              if (e.Column != sortColumn)  //first use
              {
                   // Set the sort column to the new column.
                   sortColumn = e.Column;
                   // Set the sort order to ascending by default.
                   listView1.Sorting = SortOrder.Ascending;
              }
              else //second or more use
              {
                   // Determine what the last sort order was and change it.
                   if (listView1.Sorting == SortOrder.Ascending)
                       listView1.Sorting = SortOrder.Descending;
                   else
                       listView1.Sorting = SortOrder.Ascending;
              }
 
              // Call the sort method to manually sort.
              listView1.Sort();
              // Set the ListViewItemSorter property to a new ListViewItemComparer
              // object.
              this.listView1.ListViewItemSorter = new ListViewItemComparer(e.Column,
                   listView1.Sorting);// ListViewItemCompare r 要用到下面的类
         }
一个新的类
class ListViewItemComparer : IComparer
         {
              private int col;
              private SortOrder order;
              public ListViewItemComparer()
              {
                   col=0;
                   order = SortOrder.Ascending;
              }
              public ListViewItemComparer(int column, SortOrder order)
              {
                   col=column;
                   this.order = order;
              }
              public int Compare(object x, object y)
              {
                   int returnVal= -1;
                   returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text,
                       ((ListViewItem)y).SubItems[col].Text);
                   // Determine whether the sort order is descending.
                   if(order == SortOrder.Descending)
                       // Invert the value returned by String.Compare.
                       returnVal *= -1 ;
                   return returnVal;
              }
         }
 

你可能感兴趣的:(ListView,datagrid,object,Class)