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;
}
}