我在c#中排序listview时遇到问题,我使用MSDN中的代码: https://msdn.microsoft.com/en-us/library/ms996467.aspx。 问题是,如果您有一个2位数的数字,它不能正确排序值?
请帮忙吗?
编辑:
public class ListViewItemComparer : IComparer
{
private int col;
private SortOrder order;
public ListViewItemComparer()
{
col = 0;
order = SortOrder.Ascending;
}
public ListViewItemComparer(int column, SortOrder order)
{
col = column;
this.order = order;
}
public int Compare(object x, object y)
{
int returnVal = -1;
returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text,
((ListViewItem)y).SubItems[col].Text);
// Determine whether the sort order is descending.
if (order == SortOrder.Descending)
// Invert the value returned by String.Compare.
returnVal *= -1;
return returnVal;
}
}
和:
private int sortColumn = -1;
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
// Determine whether the column is the same as the last column clicked.
if (e.Column != sortColumn)
{
// Set the sort column to the new column.
sortColumn = e.Column;
// Set the sort order to ascending by default.
listView1.Sorting = SortOrder.Ascending;
}
else
{
// Determine what the last sort order was and change it.
if (listView1.Sorting == SortOrder.Ascending)
listView1.Sorting = SortOrder.Descending;
else
listView1.Sorting = SortOrder.Ascending;
}
// Call the sort method to manually sort.
listView1.Sort();
// Set the ListViewItemSorter property to a new ListViewItemComparer
// object.
this.listView1.ListViewItemSorter = new ListViewItemComparer(e.Column,
listView1.Sorting);
}
答案 0 :(得分:2)
在MSDN上链接的示例中,这是代码:
public int Compare(object x, object y)
{
int returnVal = -1;
returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text,
((ListViewItem)y).SubItems[col].Text);
return returnVal;
}
即进行string
比较,以便将您的列排序为string
。如果类型为int
或其他数字类型,则需要修改代码以使用数字对其进行排序。这是一些代码:
public int Compare(object x, object y)
{
int returnVal = -1;
try
{
// Parse the two objects passed as a parameter as a DateTime.
int num1 =
int.Parse(((ListViewItem)x).SubItems[col].Text);
int num2 =
int.Parse(((ListViewItem)y).SubItems[col].Text);
// Compare the two numbers.
returnVal = num1.CompareTo(num2);
}
// If neither compared object has a valid int, compare
// as a string.
catch
{
// Compare the two items as a string.
returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text,
((ListViewItem)y).SubItems[col].Text);
}
// Determine whether the sort order is descending.
if (order == SortOrder.Descending)
// Invert the value returned by String.Compare.
returnVal *= -1;
return returnVal;
}