C ListView Click on the header of the data sorting function of the implementation code

  • 2021-12-12 09:31:23
  • OfStack

Add header click event


private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
    {
      if (listView1.Columns[e.Column].Tag == null)
      {
        listView1.Columns[e.Column].Tag = true;
      }
      bool tabK = (bool)listView1.Columns[e.Column].Tag;
      if (tabK)
      {
        listView1.Columns[e.Column].Tag = false;
      }
      else
      {
        listView1.Columns[e.Column].Tag = true;
      }
      listView1.ListViewItemSorter = new ListViewSort(e.Column, listView1.Columns[e.Column].Tag);
      // Specify the sorter and pass the column index and ascending and descending keywords 
      listView1.Sort();// Custom sorting of lists 
}

Classes used in sorting


public class ListViewSort : IComparer
  {
    private int col;
    private bool descK;

    public ListViewSort()
    {
      col = 0;
    }
    public ListViewSort(int column, object Desc)
    {
      descK = (bool)Desc;
      col = column; // Current column ,0,1,2..., Parameter is defined by the ListView Control's ColumnClick Event passing 
    }
    public int Compare(object x, object y)
    {
      int tempInt = String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
      if (descK)
      {
        return -tempInt;
      }
      else
      {
        return tempInt;
      }
    }
  }

Note:
Some report "Error CS0305: Using generic types" System. Collections. Generic. IComparer < T > "1 type parameter required"
At this time, only using System. Collections. Generic; Change to using System. Collections; That's enough.


Related articles: