我有一个关于ListView
排序的任务使用C#Windows窗体的列和我从MSDN获得的代码无法工作。任何人都可以找出代码有什么问题吗?每次我点击ListView
列都没有任何反应。Listview按列排序
下面的代码,我还补充说,将在我的ListView
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);
}
private void FillItems()
{
// Add items
ListViewItem item1 = new ListViewItem("Nipun Tomar");
item1.SubItems.Add("1");
item1.SubItems.Add("10/11/2000");
ListViewItem item2 = new ListViewItem("First Last");
item2.SubItems.Add("2");
item2.SubItems.Add("12/12/2010");
ListViewItem item3 = new ListViewItem("User User");
item3.SubItems.Add("3");
item3.SubItems.Add("12/01/1800");
ListViewItem item4 = new ListViewItem("Sample");
item4.SubItems.Add("4");
item4.SubItems.Add("05/30/1900");
// Add the items to the ListView.
listView1.Items.AddRange(
new ListViewItem[] {item1, item2, item3, item4});
}
private void Form1_Load(object sender, EventArgs e)
{
FillItems();
}
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;
}
}
注意显示的项目:我添加的列的设计形式。
这里是我的任务是这样的:
我编辑了我的问题。很抱歉,但没有奏效。 – Emman
@埃曼你必须在列上选择而不是项目。只有当你点击'Name'时,该事件才会触发,然后按名称排序。点击'日期',然后按日期排序。你想在点击项目时发生什么?(编辑:但是在图像中,我看到它们是由'Int'命令的,看起来它适合你) –
它不是由'int'命令的,在我的代码中'FillItems' I以这种方式进入。另外我并没有真正明白你对列的看法,因为你可以看到有一个'ColumnCLick'事件,无论何时点击一列,它都会按升序或降序排列。但我的问题是我不能看到我有一个错误。 – Emman