ListView在Detail显示时,设置其Sorting属性,是按第一列进行排序,并不能按子项进行排序
以下代码实现按各项进行排序,包括根据子项的排序(代码不够简洁,大家见谅):
//ListView标题的单击事件:排序
private void listViewRS_ColumnClick(object sender, ColumnClickEventArgs e)
{
if (e.Column == 0)//第一列
{
if (this.m_SortModeCol1 == 0)//增序
{
ListViewSorter sorter = new ListViewSorter(e.Column, 0);
this.listViewRS.ListViewItemSorter = sorter;
this.m_SortModeCol1 = 1;
this.listViewRS.Columns[0].Text = "用户助记符↑";
this.listViewRS.Columns[1].Text = "用户号码";
}
else
{
ListViewSorter sorter = new ListViewSorter(e.Column, 1);
this.listViewRS.ListViewItemSorter = sorter;
this.m_SortModeCol1 = 0;
this.listViewRS.Columns[0].Text = "用户助记符↓";
this.listViewRS.Columns[1].Text = "用户号码";
}
}
else//第二列
{
if (this.m_SortModeCol2 == 0)//增序
{
ListViewSorter sorter = new ListViewSorter(e.Column, 0);
this.listViewRS.ListViewItemSorter = sorter;
this.m_SortModeCol2 = 1;
this.listViewRS.Columns[0].Text = "用户助记符";
this.listViewRS.Columns[1].Text = "用户号码↑";
}
else
{
ListViewSorter sorter = new ListViewSorter(e.Column, 1);
this.listViewRS.ListViewItemSorter = sorter;
this.m_SortModeCol2 = 0;
this.listViewRS.Columns[0].Text = "用户助记符";
this.listViewRS.Columns[1].Text = "用户号码↓";
}
}
}
//用于ListView排序的类,继承于IComparer
public class ListViewSorter : System.Collections.IComparer
{
private int sortIndex;
private int sortMode;
public ListViewSorter(int p_SortIndex,int p_SortMode)
{
this.sortIndex = p_SortIndex;
this.sortMode = p_SortMode;
}
public int Compare(object x, object y)
{
ListViewItem item1, item2;
item1 = (ListViewItem)x;
item2 = (ListViewItem)y;
string strX, strY;
strX = item1.SubItems[this.sortIndex].ToString();
strY = item2.SubItems[this.sortIndex].ToString();
if (this.sortMode == 0)//增序
{
if (string.Compare(strX, strY) < 0)
{
return -1;
}
else if (string.Compare(strX, strY) == 0)
{
return 0;
}
else
{
return 1;
}
}
else
{
if (string.Compare(strX, strY) < 0)
{
return 1;
}
else if (string.Compare(strX, strY) == 0)
{
return 0;
}
else
{
return -1;
}
}
}
}