c#

在C#里怎样给ListView排序

小樊
103
2024-09-11 02:40:35
栏目: 编程语言

在C#中,可以使用ListView的ListViewItemSorter属性对ListView进行排序

  1. 首先,创建一个自定义的比较器类,继承自IComparer接口:
using System.Collections;

public class ListViewItemComparer : IComparer
{
    private int _column;
    private SortOrder _sortOrder;

    public ListViewItemComparer(int column, SortOrder sortOrder)
    {
        _column = column;
        _sortOrder = sortOrder;
    }

    public int Compare(object x, object y)
    {
        ListViewItem itemX = (ListViewItem)x;
        ListViewItem itemY = (ListViewItem)y;

        int result = string.Compare(itemX.SubItems[_column].Text, itemY.SubItems[_column].Text);

        if (_sortOrder == SortOrder.Descending)
            return -result;
        else
            return result;
    }
}
  1. 在你的表单上添加一个ListView控件,并为其添加列。同时,需要处理ListView的ColumnClick事件,以便在用户点击列标题时对数据进行排序。
using System;
using System.Windows.Forms;

public partial class MyForm : Form
{
    private int _sortColumn = -1;

    public MyForm()
    {
        InitializeComponent();

        listView1.Columns.Add("Name", 100);
        listView1.Columns.Add("Age", 50);

        listView1.ColumnClick += ListView1_ColumnClick;
    }

    private void ListView1_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        SortOrder sortOrder = SortOrder.Ascending;

        if (_sortColumn == e.Column)
        {
            if (listView1.Sorting == SortOrder.Ascending)
                sortOrder = SortOrder.Descending;
            else
                sortOrder = SortOrder.Ascending;
        }

        listView1.Sorting = sortOrder;
        listView1.ListViewItemSorter = new ListViewItemComparer(e.Column, sortOrder);
        listView1.Sort();

        _sortColumn = e.Column;
    }
}

现在,当用户点击ListView的列标题时,将根据所选列对数据进行升序或降序排序。

0
看了该问题的人还看了