C# ListView 정렬

2871 단어 ListViewobjectC#Class
성명
private ListViewColumnSorter lvwColumnSorter;

2 창 구조 함수 아래 코드 추가
//     ListView      ,   listView1    
lvwColumnSorter = new ListViewColumnSorter();
this.listView1.ListViewItemSorter = lvwColumnSorter;

3. listView1의 ColumnClick 이벤트에 다음 코드를 추가합니다.
//                .
if ( e.Column == lvwColumnSorter.SortColumn )
{
 //            .
 if (lvwColumnSorter.Order == SortOrder.Ascending)
 {
  lvwColumnSorter.Order = SortOrder.Descending;
 }
 else
 {
  lvwColumnSorter.Order = SortOrder.Ascending;
 }
}
else
{
 //      ,       
 lvwColumnSorter.SortColumn = e.Column;
 lvwColumnSorter.Order = SortOrder.Ascending;
}

//         ListView  
this.listView.Sort();

4.listview 정렬에 사용할 클래스 추가
using System.Collections;
using System.Windows.Forms;

/// <summary>
///    IComparer
/// </summary>
public class ListViewColumnSorter : IComparer
{
 /// <summary>
 ///          
 /// </summary>
 private int ColumnToSort;
 /// <summary>
 ///        
 /// </summary>
 private SortOrder OrderOfSort;
 /// <summary>
 ///   CaseInsensitiveComparer   ,
 ///   ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.2052/cpref/html/frlrfSystemCollectionsCaseInsensitiveComparerClassTopic.htm
 /// </summary>
 private CaseInsensitiveComparer ObjectCompare;

 /// <summary>
 ///     
 /// </summary>
 public ListViewColumnSorter()
 {
  //         
  ColumnToSort = 0;

  //         
  OrderOfSort = SortOrder.None;

  //    CaseInsensitiveComparer   
  ObjectCompare = new CaseInsensitiveComparer();
 }

 /// <summary>
 ///   IComparer  .
 /// </summary>
 /// <param name="x">         </param>
 /// <param name="y">         </param>
 /// <returns>     .      0,  x  y  1,  x  y  -1</returns>
 public int Compare(object x, object y)
 {
  int compareResult;
  ListViewItem listviewX, listviewY;

  //         ListViewItem  
  listviewX = (ListViewItem)x;
  listviewY = (ListViewItem)y;

  //   
  compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text,listviewY.SubItems[ColumnToSort].Text);

  //                   
  if (OrderOfSort == SortOrder.Ascending)
  {
   //        ,        
   return compareResult;
  }
  else if (OrderOfSort == SortOrder.Descending)
  {
   //        ,         
   return (-compareResult);
  }
  else
  {
   //       0
   return 0;
  }
 }

 /// <summary>
 ///             .
 /// </summary>
 public int SortColumn
 {
  set
  {
   ColumnToSort = value;
  }
  get
  {
   return ColumnToSort;
  }
 }

 /// <summary>
 ///          .
 /// </summary>
 public SortOrder Order
 {
  set
  {
   OrderOfSort = value;
  }
  get
  {
   return OrderOfSort;
  }
 }

}

좋은 웹페이지 즐겨찾기