Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » Windows Controls C# » Sort a Multicolumn ListView in C#

Sort a Multicolumn ListView in C#

When you are working with the ListView control, you may want to sort its contents based on a specific column. We will see how to do that.

Author Rank :
Page Views : 10188
Downloads : 261
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ListViewSortAnyColumn.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


The ListView control displays a list of items with icons. It can be used to create a user interface like the right pane of Windows Explorer. The control has four view modes: LargeIcon, SmallIcon, List, and Details. It can display a graphical icon, as well as the item text and additional information about an item in a subitem. To display subitem information in the ListView control, set View property to View.Details, create ColumnHeader objects and assign them to the Columns property of the ListView control. Once these properties are set, items are displayed in a row and column format similar to a DataGrid control. This ability makes the ListView control a quick and easy solution for displaying data from any type of data source.

When you are working with the ListView control, you may want to sort its contents based on a specific column. For this create a type that implements the System.Collection.IComparer interface. IComparer type can sort based on any ListViewItem criteria specified. Just set the ListView.ListViewItemSorter property with an instance of IComparer type and call ListView.Sort method.

Below is the ItemComparer:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Forms;

namespace ListViewSortAnyColumn
{
    public class ItemComparer : IComparer
    {
        //column used for comparison
        public int Column { get; set; }
        public ItemComparer(int colIndex)
        {
            Column = colIndex;
        }
        public int Compare(object a, object b)
        {
            int result;
            ListViewItem itemA = a as ListViewItem;
            ListViewItem itemB = b as ListViewItem;
            if (itemA == null && itemB == null)
                result = 0;
            else if (itemA == null)
                result = -1;
            else if (itemB == null)
                result = 1;
            if (itemA == itemB)
                result = 0;
            //alphabetic comparison
            result = String.Compare(itemA.SubItems[Column].Text, itemB.SubItems[Column].Text);
            return result;
        }
    }
}

And Windows Form Form1: 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ListViewSortAnyColumn
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //fill the list with data
            FillItems();
        }
        private void listViewSample_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            ItemComparer sorter = listViewSample.ListViewItemSorter as ItemComparer;
            if (sorter == null)
            {
                sorter = new ItemComparer(e.Column);
                listViewSample.ListViewItemSorter = sorter;
            }           
            else
            {
                // Set the column number that is to be sorted
                sorter.Column = e.Column;
            }
            listViewSample.Sort();
        }
        private void FillItems()
        {
            // Add items
            ListViewItem item1 = new ListViewItem("Nipun Tomar");
            item1.SubItems.Add("10/11/2000");
            item1.SubItems.Add("Email@domain.com");
            item1.SubItems.Add("123.456");

            ListViewItem item2 = new ListViewItem("First Last");
            item2.SubItems.Add("12/12/2010");
            item2.SubItems.Add("test@test.com");
            item2.SubItems.Add("123.4561");

            ListViewItem item3 = new ListViewItem("User User");
            item3.SubItems.Add("12/01/1800");
            item3.SubItems.Add("sample@Sample.net");
            item3.SubItems.Add("123.4559");

            ListViewItem item4 = new ListViewItem("Sample");
            item4.SubItems.Add("05/30/1900");
            item4.SubItems.Add("user@sample.com");
            item4.SubItems.Add("-123.456000");

            // Add the items to the ListView.
            listViewSample.Items.AddRange(
                                    new ListViewItem[] {item1,
                                                item2,
                                                item3,
                                                item4}
                                    );
    }
}

Sorting in Ascending or Descending Order

To add the ability to sort ListView items in both ascending and descending order, you need to do some changes in the above code to enable the Compare method to identify the items to sort.

So ItemComparer: 

public class ItemComparer : IComparer
{
    //column used for comparison
    public int Column { get; set; }
    //Order of sorting
    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;
        if (itemA == null && itemB == null)
            result = 0;
        else if (itemA == null)
            result = -1;
        else if (itemB == null)
            result = 1;
        if (itemA == itemB)
            result = 0;
            //alphabetic comparison
        result = String.Compare(itemA.SubItems[Column].Text, itemB.SubItems[Column].Text);
        // if sort order is descending.
        if (Order == SortOrder.Descending)
            // Invert the value returned by Compare.
            result *= -1;
        return result;
    }
}

Form1 

private void listViewSample_ColumnClick(object sender, ColumnClickEventArgs e)
{
    ItemComparer sorter = listViewSample.ListViewItemSorter as ItemComparer;
    if (sorter == null)
    {
        sorter = new ItemComparer(e.Column);
        sorter.Order = SortOrder.Ascending;
        listViewSample.ListViewItemSorter = sorter;
    }
    // if clicked column is already the column that is being sorted
    if (e.Column == sorter.Column)
    {
        // Reverse the current sort direction
        if (sorter.Order == SortOrder.Ascending)
            sorter.Order = SortOrder.Descending;
        else
            sorter.Order = SortOrder.Ascending;
    }
    else
    {
        // Set the column number that is to be sorted; default to ascending.
        sorter.Column = e.Column;
        sorter.Order = SortOrder.Ascending;
    }
    listViewSample.Sort();
}

Result (first column- Name):

1.gif
 
Sorting Dates

Data that is placed into the ListView control as an item is displayed as text and stored as text. This makes it easy to sort using the String.Compare method in an IComparer class which sorts both alphabetical characters and numbers. However, certain data types do not sort correctly using String.Compare, such as date and time information. So, you have to use the Compare method of System.DateTime structure. This method performs sorting based on chronological order. 

So ItemComparer:

...
public int Compare(object a, object b)
{
    int result;
    ListViewItem itemA = a as ListViewItem;
    ListViewItem itemB = b as ListViewItem;
    if (itemA == null && itemB == null)
        result = 0;
    else if (itemA == null)
        result = -1;
    else if (itemB == null)
        result = 1;
    if (itemA == itemB)
        result = 0;
    // datetime comparison
    DateTime x1, y1;
    // Parse the two objects passed as a parameter as a DateTime.
    if (!DateTime.TryParse(itemA.SubItems[Column].Text, out x1))
        x1 = DateTime.MinValue;
    if (!DateTime.TryParse(itemB.SubItems[Column].Text, out y1))
        y1 = DateTime.MinValue;
    result = DateTime.Compare(x1, y1);
    if (x1 != DateTime.MinValue && y1 != DateTime.MinValue)
        goto done;            
    //alphabetic comparison
    result = String.Compare(itemA.SubItems[Column].Text, itemB.SubItems[Column].Text);

    done:
    // if sort order is descending.
    if (Order == SortOrder.Descending)
        // Invert the value returned by Compare.
        result *= -1;
    return result;
    }
}

Result (second column- Date):

2.gif 

Sorting Decimals

Similar to Dates you may also have decimal data into the ListView control. For this to work properly, you have to use the Compare method of System.Decimal structure.

So finally ItemComparer:

public int Compare(object a, object b)
{
    int result;
    ListViewItem itemA = a as ListViewItem;
    ListViewItem itemB = b as ListViewItem;
    if (itemA == null && itemB == null)
        result = 0;
    else if (itemA == null)
        result = -1;
    else if (itemB == null)
        result = 1;
    if (itemA == itemB)
        result = 0;
    // datetime comparison
    DateTime x1, y1;
    // Parse the two objects passed as a parameter as a DateTime.
    if (!DateTime.TryParse(itemA.SubItems[Column].Text, out x1))
        x1 = DateTime.MinValue;
    if (!DateTime.TryParse(itemB.SubItems[Column].Text, out y1))
        y1 = DateTime.MinValue;
    result = DateTime.Compare(x1, y1);
    if (x1 != DateTime.MinValue && y1 != DateTime.MinValue)
        goto done;
    //numeric comparison
    decimal x2, y2;
    if (!Decimal.TryParse(itemA.SubItems[Column].Text, out x2))
        x2 = Decimal.MinValue;
    if (!Decimal.TryParse(itemB.SubItems[Column].Text, out y2))
        y2 = Decimal.MinValue;
    result = Decimal.Compare(x2, y2);
    if (x2 != Decimal.MinValue && y2 != Decimal.MinValue)
        goto done;
    //alphabetic comparison
    result = String.Compare(itemA.SubItems[Column].Text, itemB.SubItems[Column].Text);

    done:
    // if sort order is descending.
    if (Order == SortOrder.Descending)
        // Invert the value returned by Compare.
        result *= -1;
    return result;
}

Result (last Column- Points):

3.gif

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Nipun Tomar

Nipun is competent and experienced "project leader", with "8 years" of experience in managing multi-disciplinary teams of varying sizes and complex programs of work. Has the ability to build strong relationships with all stakeholders and to turn proposals into reality.

"Especially successful in management roles that demand rigor, a high level of drive and dedication and a focus on delivering business outcomes through the use of methodologies".

Strengths include successful analysis and problem-solving expertise, highly rated oral and written communications skills, and proven project management experience. Strong background in "C#, Visual Studio 2010, ASP.NET, Windows Forms, WPF, WCF, Silverlight and SQL Server".

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Question: SortDirection Icons by Zolton On December 4, 2010
Hi Nipun,

Do you know how to get the SortDirection icons to appear using 100% managed code and using a CLS compliant assembly?

Zolton
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.