我怎么排序在ListView整数 [英] how do I sort Integers in a listview

查看:150
本文介绍了我怎么排序在ListView整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在ListView排序整数列

How do I sort columns of integers in a ListView

C#.NET 2.0的Winform

c#, .net 2.0, Winform

System.Windows.Forms.ListView

System.Windows.Forms.ListView

推荐答案

这是我如何完成能够排序多列,并能每列排序为数字,或文本。

This is how I accomplished being able to sort on multiple columns, and being able to sort each column as a number, or as text.

首先使用这个类:

class Sorter : System.Collections.IComparer
{
    public int Column = 0;
    public System.Windows.Forms.SortOrder Order = SortOrder.Ascending;
    public int Compare(object x, object y) // IComparer Member
    {
        if (!(x is ListViewItem))
            return (0);
        if (!(y is ListViewItem))
            return (0);

        ListViewItem l1 = (ListViewItem)x;
        ListViewItem l2 = (ListViewItem)y;

        if (l1.ListView.Columns[Column].Tag == null)
        {
            l1.ListView.Columns[Column].Tag = "Text";
        }

        if (l1.ListView.Columns[Column].Tag.ToString() == "Numeric")
        {
            float fl1 = float.Parse(l1.SubItems[Column].Text);
            float fl2 = float.Parse(l2.SubItems[Column].Text);

            if (Order == SortOrder.Ascending)
            {
                return fl1.CompareTo(fl2);
            }
            else
            {
                return fl2.CompareTo(fl1);
            }
        }
        else
        {
            string str1 = l1.SubItems[Column].Text;
            string str2 = l2.SubItems[Column].Text;

            if (Order == SortOrder.Ascending)
            {
                return str1.CompareTo(str2);
            }
            else
            {
                return str2.CompareTo(str1);
            }
        }
    }
}

在你的窗体的构造,设置分拣机是这样的:

In your form's constructor, set the sorter like this:

lvSeries.ListViewItemSorter = new Sorter();

然后处理甚至你这样的ListView控件ColumnClick:

Then handle the ColumnClick even of your listview control like this:

private void lvSeries_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        Sorter s = (Sorter)lvSeries.ListViewItemSorter;
        s.Column = e.Column;

        if (s.Order == System.Windows.Forms.SortOrder.Ascending)
        {
            s.Order = System.Windows.Forms.SortOrder.Descending;
        }
        else
        {
            s.Order = System.Windows.Forms.SortOrder.Ascending;
        }
        lvSeries.Sort();
    }

这是所有依赖于每一列的标签属性要么被设置为数字或没有,所以分拣机知道如何进行排序。

This is all dependent on the Tag property of each column either being set to "Numeric" or not, so the sorter knows how to sort.

在上面的例子中,我投的值作为花车的数字时,你可能会想改变这种状况为int。

In the above example I cast the values as floats when numeric, you may want to change that to int.

这篇关于我怎么排序在ListView整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆