ListView排序總結

來源:互聯網
上載者:User

 ListView排序總結;
ListView的排序還存在一個問題沒有解決,當第一列為序號時,要始終保持序號為升序,應該怎樣解決?

當Column為動態時,排序會報錯,把//this.listView1.ListViewItemSorter = null;放在更新Column之前,就可以解決!
 private int CurrentColumn = -1; //記錄上次點擊的列號
  private bool b_Convert = false; //記錄正逆序資訊
  private void listView1_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
  {
   if(e.Column == CurrentColumn)
   {
    b_Convert = ! b_Convert;
    if(e.Column == 3 ||e.Column == 0)
     this.listView1.ListViewItemSorter = new SortBySubItem(e.Column,b_Convert,1);//數值排序
    else
     this.listView1.ListViewItemSorter = new SortBySubItem(e.Column,b_Convert);//字元排序
   }
   else
   {
    CurrentColumn = e.Column;
    b_Convert = false;
    if(e.Column == 3||e.Column == 0)
     this.listView1.ListViewItemSorter = new SortBySubItem(e.Column,b_Convert,1);
    else
     this.listView1.ListViewItemSorter = new SortBySubItem(e.Column,b_Convert);
   }
  }
 }

 public class SortBySubItem : System.Collections.IComparer
 {
  private int m_Column = 0;
  private int m_SortType = 0;//排序類型
  private bool m_asc = true;
  public SortBySubItem(int Column,bool bAsc)
  {
   m_Column = Column;
   m_asc = bAsc;
  }
  public SortBySubItem(int Column,bool bAsc, int SortType)
  {
   m_Column = Column;
   m_SortType = SortType;
   m_asc = bAsc;
  }
  int IComparer.Compare(object x, object y)
  {
   string item1 = ((ListViewItem)x).SubItems[m_Column].Text.Trim();
   string item2 = ((ListViewItem)y).SubItems[m_Column].Text.Trim();
   int intSort = 0;
   if(!m_asc)//反序
   {
    string temp = item1;
    item1 = item2;
    item2 = temp;
   }

   if(m_SortType == 0)   //字元排序
    intSort = String.Compare(item1,item2);
   else      //數值排序
   {
    double str1 = 0;
    double str2 = 0;
    if(item1 == "")//為空白設定為最小
     return 1;
    else if(item2 == "")
     return 0;
    try
    {
     str1 = double.Parse(item1);
     str2 = double.Parse(item2);
    }
    catch
    {
     //轉換出錯
     return 0;
    }
    if(str1 >=str2)
     return 0;
    else
     return 1;
    
   }
   return intSort;
  }
 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.