PDA

View Full Version : Help with Making ListView Columns Sortable in VC++ 2005


That Asian Guy
13th December 2007, 02:12
I understand that there is a property with listviews where u can change the sorting type, such as ascending.



However, this automatic sorting method is unuseful if the type of sorting is user-controlled. There are many programs which have a column sorting method, such that the column will automatically sort when you click on the column header.



What code do I have to insert for the column header to become sortable when clicked.



I have tried:



private: System::Void listView1_ColumnClick(System:: Object^ sender, System::Windows::Forms::ColumnClickEventArgs^ e)

{

listView1->Sorting=SortOrder::Ascending

}





However, the column header does not show an arrow like many other programs ex:

http://img68.imageshack.us/img68/6827/23161253yn6.png



What property or code do I have to insert to make column headers sortable?

EDIT: nvm answered on Microsoft forums:

public partial class Form15 : Form

{

public Form15()

{

InitializeComponent();

}



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 Form15_Load(object sender, EventArgs e)

{

this.listView1.DrawColumnHeader +=
new DrawListViewColumnHeaderEventHandler(listView1_Dra wColumnHeader);

}



void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)

{

if (e.ColumnIndex == this.sortColumn)

{

if (this.listView1.Sorting == SortOrder.Ascending)

{

//draw arrow image here

}

}

}

}



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;

}

}