jeudi, décembre 15, 2005

ListView sorting


private int sortColumn = -1;

//List view click event
private void listView_ColumnClick(object sender, System.Windows.Forms.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.
listViewAllMissions.Sorting = SortOrder.Ascending;
}
else
{
// Determine what the last sort order was and change it.
if (listViewAllMissions.Sorting == SortOrder.Ascending)
listViewAllMissions.Sorting = SortOrder.Descending;
else
listViewAllMissions.Sorting = SortOrder.Ascending;
}

// Call the sort method to manually sort.
listViewAllMissions.Sort();
// Set the ListViewItemSorter property to a new ListViewItemComparer
// object.
this.listViewAllMissions.ListViewItemSorter = new ListViewItemComparer(e.Column,
listViewAllMissions.Sorting);
}

//Compare class
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;
}
}

Aucun commentaire: