ListView sorting summary;
A problem still persists in sorting ListView. When the first column is the serial number, the sequence number must always be in ascending order. How can this problem be solved?
When Column is dynamic, an error will be reported in sorting. Put // this. listView1.ListViewItemSorter = null; before updating Column, you can solve this problem!
Private int CurrentColumn =-1; // record the column number that was last clicked
Private bool B _Convert = false; // records positive and reverse order information
Private void listView1_ColumnClick (object sender, System. Windows. Forms. ColumnClickEventArgs e)
{
If (e. Column = CurrentColumn)
{
B _Convert =! B _Convert;
If (e. Column = 3 | e. Column = 0)
This. listView1.ListViewItemSorter = new SortBySubItem (e. Column, B _Convert, 1); // sort values
Else
This. listView1.ListViewItemSorter = new SortBySubItem (e. Column, B _Convert); // sort the characters
}
Else
{
CurrentColumn = e. Column;
B _Convert = false;
If (e. Column = 3 | e. Column = 0)
This. listView1.ListViewItemSorter = new SortBySubItem (e. Column, B _Convert, 1 );
Else
This. listView1.ListViewItemSorter = new SortBySubItem (e. Column, B _Convert );
}
}
}
Public class SortBySubItem: System. Collections. IComparer
{
Private int m_Column = 0;
Private int m_SortType = 0; // sorting type
Private bool m_asc = true;
Public SortBySubItem (int Column, bool bAsc)
{
M_Column = Column;
M_asc = bAsc;
}
Public SortBySubItem (int Column, bool bAsc, int SortType)
{
M_Column = Column;
M_SortType = SortType;
M_asc = bAsc;
}
Int IComparer. Compare (object x, object y)
{
String item1 = (ListViewItem) x). SubItems [m_Column]. Text. Trim ();
String item2 = (ListViewItem) y). SubItems [m_Column]. Text. Trim ();
Int intSort = 0;
If (! M_asc) // Reverse Order
{
String temp = item1;
Item1 = item2;
Item2 = temp;
}
If (m_SortType = 0) // sort the characters
IntSort = String. Compare (item1, item2 );
Else // numerical sorting
{
Double str1 = 0;
Double str2 = 0;
If (item1 = "") // if it is null, set it to the minimum value.
Return 1;
Else if (item2 = "")
Return 0;
Try
{
Str1 = double. Parse (item1 );
Str2 = double. Parse (item2 );
}
Catch
{
// Conversion error
Return 0;
}
If (str1> = str2)
Return 0;
Else
Return 1;
}
Return intSort;
}
}