ListView列排序功能实现


  #region/***lv列排序***/
  private void ColumnClick(object o, ColumnClickEventArgs e)
  {
   try
   {
    lv_examView.ListViewItemSorter = new ListViewItemComparer(e.Column,lv_examView.Sorting);
    lv_examView.Sort();
    if(lv_examView.Sorting == SortOrder.Ascending)
     lv_examView.Sorting = SortOrder.Descending;
    else
     lv_examView.Sorting = SortOrder.Ascending;
   }
   catch(Exception err)
   {
    MessageBox.Show(this,err.Message,"列排序",MessageBoxButtons.OK,MessageBoxIcon.Error);
   }
  }
  #endregion

 #region/***列排序类***/
  class ListViewItemComparer : IComparer
  {
   private int col;
   private SortOrder is_sortOrder = SortOrder.Ascending;
   public ListViewItemComparer()
   {
    col=0;
   }
   public ListViewItemComparer(int column, SortOrder sortOrder)
   {
    col=column;
    is_sortOrder = sortOrder;
   }
   public int Compare(object x, object y)
   {
    int result=0;
    try
    {

      result= String.Compare(((ListViewItem)x).SubItems[col].Text,((ListViewItem)y).SubItems[col].Text);

//     switch (col)
//     {
//
//      case 3 :
//       string text=((ListViewItem)x).SubItems[col].Text.ToString();
//       string texty=((ListViewItem)y).SubItems[col].Text.ToString();
//       decimal dm1=ChangeBytesBack(text);
//       decimal dm2=ChangeBytesBack(texty);
//       result= Decimal.Compare(dm1,dm2);
//       break;
//
//      default :
//       result= String.Compare(((ListViewItem)x).SubItems[col].Text,((ListViewItem)y).SubItems[col].Text);
//       break;
//     }
    }
    catch(Exception err)
    {
     throw new Exception(err.Message);
    }
    if (is_sortOrder == SortOrder.Descending)
     return result;
    else
     return -result;
   }

   //字节转换
   private  decimal  ChangeBytesBack(string oldstr)
   {
    decimal filelength=0;
    try
    {
     string strExplain=oldstr.Substring(oldstr.Length-2);
     decimal  lDSize = Convert.ToDecimal(oldstr.Substring(0,oldstr.Length-3));

     try
     {
      switch(strExplain)
      {
       case "KB":
        filelength=lDSize*1024;
        break;
       case "MB":
        filelength=lDSize*1024*1024;
        break;
       case "GB":
        filelength=lDSize*1024*1024*1024;
        break;
      }
  
     } 
     catch (Exception err)
     {
      throw new Exception(err.Message);
     }
    }
    catch(Exception err)
    {
     throw new Exception(err.Message);
    }

    return filelength;
   }
 
   #endregion
  }

转载于:https://www.cnblogs.com/flashicp/archive/2007/01/25/ddselina.html

你可能感兴趣的:(ListView列排序功能实现)