c#

c# listviewitem如何实现多列排序

小樊
99
2024-07-15 15:27:40
栏目: 编程语言

在C#中,使用ListView控件来实现多列排序时,可以通过自定义排序函数来实现。以下是一个示例代码,演示如何在ListView中实现多列排序:

using System;
using System.Windows.Forms;
using System.Collections;

public partial class Form1 : Form
{
    private int sortColumn = -1;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // 添加列
        listView1.Columns.Add("Column1", 100);
        listView1.Columns.Add("Column2", 100);
        listView1.Columns.Add("Column3", 100);

        // 添加数据
        ListViewItem item1 = new ListViewItem(new string[] { "A", "C", "B" });
        ListViewItem item2 = new ListViewItem(new string[] { "C", "A", "B" });
        ListViewItem item3 = new ListViewItem(new string[] { "B", "A", "C" });

        listView1.Items.Add(item1);
        listView1.Items.Add(item2);
        listView1.Items.Add(item3);

        // 添加事件处理程序
        listView1.ColumnClick += new ColumnClickEventHandler(ListView_ColumnClick);
    }

    private void ListView_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        if (e.Column != sortColumn)
        {
            sortColumn = e.Column;
            listView1.Sorting = SortOrder.Ascending;
        }
        else
        {
            if (listView1.Sorting == SortOrder.Ascending)
            {
                listView1.Sorting = SortOrder.Descending;
            }
            else
            {
                listView1.Sorting = SortOrder.Ascending;
            }
        }

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

    // 自定义排序类
    public class ListViewItemComparer : IComparer
    {
        private int column;
        private SortOrder order;

        public ListViewItemComparer(int column, SortOrder order)
        {
            this.column = column;
            this.order = order;
        }

        public int Compare(object x, object y)
        {
            int result = String.Compare(((ListViewItem)x).SubItems[column].Text, ((ListViewItem)y).SubItems[column].Text);

            if (order == SortOrder.Descending)
            {
                result = -result;
            }

            return result;
        }
    }
}

在上面的示例代码中,通过自定义一个ListViewItemComparer类来实现多列排序。在ListView_ColumnClick事件处理程序中,根据点击的列和排序顺序来创建ListViewItemComparer对象,并将其赋值给ListView.ListViewItemSorter属性,实现按照指定列和顺序进行排序。

0
看了该问题的人还看了