View Products That Article Applies To.
Article ID: 319401Last Review: January 18, 2006Revision: 2.0
This Article Was Previously Published Under Q319401
On this Page
Summary how to build the sample projectapplies to
Summary
This Step-by-Step Article Describes How To Sort A
Listview control by a column in your visitual c # application.
When you are working with the
ListView control, you may want to sort its contents based on a specific column. An example of this kind of functionality occurs in a Windows Explorer program when you view the contents of a folder on your hard disk. In Details view, Windows Explorer displays information about the files in that folder. For example, you see the file name, the file size, the file type, and the date that the file was modified. When you click one of the column headers, the list is sorted in ascending order based ON That Column. When You Click The Same Column Header Again, The Column IS Sorted in Descending Order.
THE EXAMPLE IN THIS ARTICLE Defines a class what inherits from the
IComparer Interface. Additionally, this Example Uses the
Compare Method of the
CaseInsenstiveComparer class to perform the actual comparison of the items. Note that this method of comparison is not case sensitive ( "Apple" is considered to be the same as "apple"). Also, note that all of the columns in this example are sorted IN A "Text" Manner. if you want to sort in a Different Manner (Such as numericly), You Can Replace The Following Line of Code With Whichever Approach To Sorting That You Want To Use:
Objectcompare.compare (listviewx.subitems [columntosort] .text, listviewy.subitems [columntosort] .text);
Back to the top
How to build the sample project
1.Create a new Visual C # Windows application project. Form1 is created by default.2.Add a ListView control to Form1. Size the form to be several inches wide by several inches tall.3.Paste the following code into the class for the form: private ListViewColumnSorter lvwColumnSorter; 4.Paste the following code into the constructor for the form, after the call to the InitializeComponent method: // Create an instance of a ListView column sorter and assign it
// TO The ListView Control.
LvwcolumnsORTER = New ListViewColumnsORTER ();
This.listview1.listviewItemsORTER = LVWCOLUMNSORTER;
5.Paste The Following Code Into The Load Event for the form: ColumnHeader ColumnHeader; // subsid for creating column headers.
ListViewItem ListViewItem; // Used for Creating ListView Items.
// EnSure That The View is set to show details.
ListView1.view = view.details;
// Create Some ListView Items Consisting of First and Last Names.
ListviewItem = New ListViewItem ("john");
ListViewItem.SubItems.Add ("smith");
This.ListView1.Items.Add (ListViewItem);
ListviewItem = New ListViewItem ("Bob");
ListViewItem.SubItems.add ("taylor");
This.ListView1.Items.Add (ListViewItem);
ListviewItem = New ListViewItem ("kim");
ListviewItem.Subitems.Add ("zimmerman");
This.ListView1.Items.Add (ListViewItem);
ListviewItem = New ListViewItem ("Olivia");
ListviewItem.Subitems.Add ("johnson");
This.ListView1.Items.Add (ListViewItem);
// Create Some Column Headers for the Data.
ColumnHeader = new columnheader ();
ColumnHeader.Text = "first name";
This.ListView1.columns.add (ColumnHead);
ColumnHeader = new columnheader ();
ColumnHeader.Text = "Last Name"; this.listview1.columns.add (color);
// Loop through and size each column header to fit the column header text.
Foreach (ColumnHeader Chin this.listview1.columns)
{
Ch.Width = -2;
}
Note The code should be changed in Visual Studio 2005. When you create a Windows Forms project, Visual C # adds one form to the project by default. This form is named Form1. The two files that represent the form are named Form1.cs and Form1 .designer.cs. you write your code in Form1.cs. The Designer.cs file is where the Windows Forms Designer writes the code that implements all the actions that you performed by adding controls. For more information about the Windows Forms Designer in Visual C # 2005, Visit The Following Microsoft Web Site:
Http://msdn2.microsoft.com/en-us/library/ms173077.aspx
(http://msdn2.microsoft.com/en-us/library/ms173077.aspx)
6.Paste The Following Code Into The ColumnClick Event for the listview control: // determine10.. ''
IF (e.column == lvwcolumnoster.sortcolumn)
{
// Reverse The Current Sort Direction for this Column.
IF (lvwcolumnoster.order == sortorder.ascending)
{
LvwcolumnsORTER.Order = sortorder.descending;
}
Else
{
LvwcolumnsORTER.Order = Sortorder.ascending;
}
}
Else
{
// set the column number what is to be sorted; default to couch.
Lvwcolumnsorter.sortcolumn = E.COLUMN;
LvwcolumnsORTER.Order = Sortorder.ascending;
}
// Perform The Sort with these New Sort Options.
THISTVIEW1.SORT ();
7.On the Project menu, click Add Class to add a new class to the project.8.Replace all of the default code in the new class with the following code: using System.Collections; using System.Windows.Forms;
///
/// this class is an information of the 'iComparer' interface.
/// summary>
Public Class ListViewColumnsRer: IComparer
{
///
/// specifies the colorn to be sorted
/// summary>
Private int columntosort;
///
/// specifies the order in which to sort (i.e. 'ascending').
/// summary>
Private sortorder orderofs;
///
/// case insensitive Comparer Object
/// summary>
Private caseinsensitiveComparer ObjectCompare;
///
/// Class Constructionor. Initializes Various Elements
/// summary>
Public ListViewColumnsR ()
{
// Initialize the colorn to '0'
ColumnOstosort = 0;
// Initialize the sort order to 'none'
OrderOfsort = Sortorder.none;
// Initialize the CaseinsensitiveComparer Object
Objectcompare = new caseinsensitivecomparer ();
}
///
/// this method is inherited from the iComparer Interface. It Compares The Two Objects Passed USING A CASE INSENSITIVE COMPARISON.
/// summary>
/// First Object to be compared param>
/// Second Object to be compared param>
///
Public Int Compare (Object X, Object Y)
{
Int compareresult;
ListViewItem ListViewX, ListViewy; // Cast the Objects To Be Compared to ListviewItem Objects
ListViewx = (listviewItem) x;
ListViewY = (listviewItem) Y;
// Compare the Two Items
Compareresult = ObjectCompare.comPare (listviewx.subitems [columntosort] .text, listviewy.subitems [columntosort] .text);
// Calculate Correct Return Value Based ON Object Comparison
IF (ORDEROFSORT == Sortorder.ascending)
{
// ascending sort is selected, return normal result of compare Operation
Return Compareresult;
}
Else IF (ORDEROFSORT == Sortorder.Descending)
{
// Descending Sort is SELECTED, RETURN NEGATIVE RESULT OF Compare Operation
Return (-compareresult);
}
Else
{
// Return '0' to Indicate They Are Equal
Return 0;
}
}
///
/// Gets or sets the number of the column to which to apply the sorting operation (defaults to '0').
/// summary>
Public int Sortcolumn
{
set
{
Columntosort = value;
}
get
{
Return ColumnTosort;
}
}
///
/// Gets or sets the order of sorting to apply (for example, 'ascending' or 'descending ").
/// summary>
Public Sortorder ORDER
{
set
{
ORDEROFSORT = VALUE;
}
get
{
Return ORDEROFSORT;
}
}
}
9.Save, build, and then run the sample project.10.Click the various column headers in the ListView control. When you click the header, the contents of the ListView control are sorted in ascending order based on the column that you click. WHEN You Click The Same Column Header Again, That Column is sorted in descending order.