Proton
Proton

Reputation: 93

Sorting ListView Items for 1 column as integer?

I want to sort one column in my ListView as an integer, because if i want to sort them i get the result.

If i try to sort them i just get this. I think the reason is, that they are compared as strings?

1 10 11 12 2 20 21 3

I want them to be sorted like this:

1 2 3 4 5 10 11 20

and so on ...

This is my class to compare the items:

public class ItemComparer : IComparer
{
    public int Column { get; set; }

    public SortOrder Order { get; set; }

    public ItemComparer(int colIndex)
    {
        Column = colIndex;
        Order = SortOrder.None;
    }
    public int Compare(object a, object b)
    {
        int result;

        ListViewItem itemA = a as ListViewItem;
        ListViewItem itemB = b as ListViewItem;

        result = String.Compare(itemA.SubItems[Column].Text, itemB.SubItems[Column].Text);

        if (Order == SortOrder.Descending)
        {
            result *= -1;
        }
        else
        {
            return -1;
        }
        return result;
    }
}

in Form:

ItemComparer sorter = listView_Data.ListViewItemSorter as ItemComparer;

if(sorter == null)
{
    sorter = new ItemComparer(e.Column);
    sorter.Order = SortOrder.Ascending;
    listView_Data.ListViewItemSorter = sorter;
}
if(e.Column == sorter.Column)
{
    if(sorter.Order == SortOrder.Ascending)
    {
        sorter.Order = SortOrder.Descending;
    }
    else
    {
        sorter.Order = SortOrder.Ascending;
    }
}
else
{
    sorter.Column = e.Column;
    sorter.Order = SortOrder.Ascending;
}
listView_Data.Sort();

How can i add for column 1, where the id from the database is a integer sort, so that they are sorted like above?

Upvotes: 1

Views: 1735

Answers (1)

selkathguy
selkathguy

Reputation: 1171

result = String.Compare(itemA.SubItems[Column].Text, itemB.SubItems[Column].Text);

Why not just use the values directly, if they are indeed just integers?

result = Int32.Parse(itemA.SubItems[Column].Text) - Int32.Parse(itemB.SubItems[Column].Text);

You may need some additional logic to check the columns so that you're not trying to parse integers from columns containing words though.

Upvotes: 2

Related Questions