欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# listview 点击列头排序的实例

程序员文章站 2022-11-21 11:52:11
实例如下: #region 自定义变量 int currentcol = -1; bool sort; #endregion//列头点击事件...

实例如下:

#region 自定义变量
  int currentcol = -1;
  bool sort;
  #endregion//列头点击事件

private void lvw_columnclick(object sender, columnclickeventargs e)
  {
   string asc = ((char)0x25bc).tostring().padleft(4, ' ');
   string des = ((char)0x25b2).tostring().padleft(4, ' ');

   if (sort == false)
   {
    sort = true;
    string oldstr = this.lvw.columns[e.column].text.trimend((char)0x25bc, (char)0x25b2, ' ');
    this.lvw.columns[e.column].text = oldstr + des;
   }
   else if (sort == true)
   {
    sort = false;
    string oldstr = this.lvw.columns[e.column].text.trimend((char)0x25bc, (char)0x25b2, ' ');
    this.lvw.columns[e.column].text = oldstr + asc;
   }

   if(lvw.columns[e.column].tag.tostring()=="n")//在设计器中把列头的tag设为"n",则表示该列按数字比较器处理,否则为文本
    lvw.listviewitemsorter = new listviewitemcomparernum(e.column, sort);
   else
    lvw.listviewitemsorter = new listviewitemcomparer(e.column, sort);
   this.lvw.sort();
   int rowcount = this.lvw.items.count;
   if (currentcol != -1)
   {
    if (e.column != currentcol)
     this.lvw.columns[currentcol].text = this.lvw.columns[currentcol].text.trimend((char)0x25bc, (char)0x25b2, ' ');
   }
   currentcol = e.column;
  }//文本比较器public class listviewitemcomparer : icomparer
  {
   public bool sort_b;
   public sortorder order = sortorder.ascending;

   private int col;

   public listviewitemcomparer()
   {
    col = 0;
   }

   public listviewitemcomparer(int column, bool sort)
   {
    col = column;
    sort_b = sort;
   }

   public int compare(object x, object y)
   {
    if (sort_b)
    {
     return string.compare(((listviewitem)x).subitems[col].text, ((listviewitem)y).subitems[col].text);
    }
    else
    {
     return string.compare(((listviewitem)y).subitems[col].text, ((listviewitem)x).subitems[col].text);
    }
   }
  }  //数字比较器
  public class listviewitemcomparernum : icomparer
  {
   public bool sort_b;
   public sortorder order = sortorder.ascending;

   private int col;

   public listviewitemcomparernum()
   {
    col = 0;
   }

   public listviewitemcomparernum(int column, bool sort)
   {
    col = column;
    sort_b = sort;
   }

   public int compare(object x, object y)
   {
    decimal d1=convert.todecimal(((listviewitem)x).subitems[col].text);
    decimal d2=convert.todecimal(((listviewitem)y).subitems[col].text);
    if (sort_b)
    {
     return decimal.compare(d1,d2);
    }
    else
    {
     return decimal.compare(d2,d1);
    }
   }
  }

以上这篇c# listview 点击列头排序的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。