Use vb.net to sort Windows Form by column ListView items

Source: Internet
Author: User
Tags class definition constructor contains file size file system integer sort valid
window| Sort | Project use Windows Form to sort ListView items by column

Summary: Explains how to provide a sort of project based on the columns you click in the ListView control in Microsoft. NET.

Brief introduction

The ListView control is a great way to display file system information and display XML or database data. ListView controls are typically used to display graphical icons that represent items as well as project text. In addition, the ListView control can be used to display additional information about items in subprojects. For example, if the ListView control displays a list of files, you can configure the ListView control to display detailed information such as the file size and properties as a subproject. To display the subproject information in a ListView control, you must set the View property to View.Details. In addition, you must create ColumnHeader objects and assign them to the Columns properties of the ListView control. After you set these properties, the items are displayed in row and column format, similar to the DataGrid control. The ability to display items in this way enables the ListView control to provide a quick and easy solution for displaying data from any type of data source.

Sorting the ListView control is provided by using the sorting property of ListView. This allows you to define the sort type to apply to the project. This is a very good feature if you want to sort by project only. If you want to sort by subproject, you must use the custom sort feature of the ListView control. This article explains how to perform custom sorting in a ListView control, and how to handle special data type conditions when sorting.



Custom sort functionality for ListView controls

The ListView control provides functionality that you can use to sort instead of being provided by the sorting property. When the ListView control uses the sorting property to sort items, it uses a class that implements the System.Collections.IComparer interface. This class provides a sorting function for sorting each item. To sort by subprojects, you must create your own classes to implement IComparer interfaces that, in turn, can implement the sort required for the ListView control. This class is defined using constructors that specify the columns used by the ListView control to sort. After you create this class (usually as a nested class for a form), you can create an instance of the class and assign it to the ListView Listviewitemsorter property. When you call the Sort method, this determines the custom sort class that the ListView control will use. The Sort method performs the actual sort of the ListView project.

Ascending sort

The basic examples provided in the following sections illustrate the sort based on its subprojects in the ListView control. The example shows the items in the ListView control sorted in ascending order. Ascending or descending sort will be explained later in this article. The goal here is to explain the basic requirements for custom sorting in the ListView control.

Initializing controls

If you want to start, create an instance of the ListView control and add it to the form. After the control is on the form, use the Items property to add the item to the ListView control. You can add as many items as you want to make sure that the text for each item is unique. When you create a project, add two subprojects to each project. The first subproject should contain numeric information, and the second subproject contains date information. The following table example shows how this information might appear in the ListView control.

Project
Sub Item 1
Sub Item 2

Alpha
1.0
4/5/1945

Charlie
3.5
1/9/1920

Bravo
2.4
12/8/1930


Create two ColumnHeader objects and assign them to the Columns property of the ListView control. Set the View property to View.Details.

Handling Columnclick Events

To determine which subproject set to sort by, you need to know when the user clicks a column heading for a child item. To do this, you need to create an event-handling method for the ListView Columnclick event. Use an event-handling method as a member of a form, and make sure that it contains a signature similar to the one shown in the following code example.

' Visual Basic

Private Sub Listview1_columnclick (sender as Object, E as System.Windows.Forms.ColumnClickEventArgs)

End Sub

C#

private void Listview1_columnclick (object sender, System.Windows.Forms.ColumnClickEventArgs e)

{

}

Connect the event-handling method to the ListView control by adding code to the form's constructor, as shown in the following example.

' Visual Basic

AddHandler Listview1.columnclick, AddressOf Me.listview1_columnclick

C#

This.listView1.ColumnClick + = new System.Windows.Forms.ColumnClickEventHandler (This.listview1_columnclick);

Add the following code to the event-handling method for the Columnclick event.

' Visual Basic

' Set the Listviewitemsorter ' to a new listviewitemcomparer

' Object.

Me.listView1.ListViewItemSorter = New ListViewItemComparer (e.column)

' Call the ' sort method to manually sort.

Listview1.sort ()

C#

Set the Listviewitemsorter property to a new ListViewItemComparer

Object.

This.listView1.ListViewItemSorter = new ListViewItemComparer (e.column);

Call the Sort method to manually sort.

Listview1.sort ();

The code added to the event-handling method uses a new instance of the ListViewItemComparer class (defined in the next section) to set the Listviewitemsorter property of the ListView control, and then assign the column to be clicked. The clicked column is passed as part of the event parameter. After you set the Listviewitemsorter property, call the sort method to perform a manual sort.

Create ListViewItemComparer Class

As mentioned earlier, the key to custom sorting in the ListView control is to create a class that implements the System.Collections.IComparer interface. This is the class that provides the sort for the project. For this example, the class named ListViewItemComparer is defined and added as a nested class for the form. ListViewItemComparer performs a basic ascending sort of the specified column passed to its constructor. Add the following class definition to the Form class and make sure it is nested correctly within the window.

' Visual Basic

' Implements the manual sorting of items by column.

Class ListViewItemComparer

Implements IComparer

Private Col as Integer



Public Sub New ()

Col = 0

End Sub



Public Sub New (column as Integer)

col = column

End Sub



Public Function Compare (x As Object, y as Object) as Integer _

Implements System.Collections.IComparer.Compare

Dim ReturnVal as Integer =-1

ReturnVal = [String]. Compare (CType (x, _

ListViewItem). SubItems (COL). Text, _

CType (y, ListViewItem). SubItems (COL). Text)

Return ReturnVal

End Function

End Class

C#

Implements the manual sorting of items by column.

Class Listviewitemcomparer:icomparer {

private int col;

Public ListViewItemComparer () {

col=0;

}

public listviewitemcomparer (int column)

{

Col=column;

}

public int Compare (object x, Object y)

{

int returnval =-1;

ReturnVal = String.Compare ((listviewitem) x). Subitems[col]. Text,

((ListViewItem) y). Subitems[col]. Text);

return returnval;

}

}

Performs a sort with the necessary method of a IComparer interface named Compare. This method takes two objects as arguments, and the parameters contain the two items to compare. When you call the Sort method in the Columnclick event-handling method of the ListView control, the Sort method uses the ListViewItemComparer object that is defined and assigned to the Listviewitemsorter property, and calls its Com Pare method. The index of the column that was assigned to the ListViewItemComparer object after it was created. The index of this column is used to access subprojects from columns that need to be sorted. The subproject is then passed to the String.Compare method, which compares the project and returns one of the three results. If the item in the X argument is less than the item in the y parameter, a value less than 0 is returned. If two items are the same, zero is returned. Finally, if the value in the x parameter is greater than the value in the y parameter, a value greater than 0 is returned. The value returned by the Compare method is passed back to the Sort method, which determines the position of each item being compared in the column. The sort method can call the Compare method as many times as necessary to sort all the subprojects in the selected column.

The previous example is complete. If you run the example and click the column headings of the ListView control, the items are sorted in alphabetical order or in numerical order. The only column that is not sorted correctly is the column that contains the date information. Later in this article we will describe the sort date columns.

This example illustrates the basic elements required to perform a basic manual project sort in a ListView control. The next section expands the example to provide ascending and descending sort functionality.

Sort Ascending or descending order

Users of the ListView control will expect to have the ability to sort items in both ascending and descending order. To do this, you need to make some changes to the previous example so that the Compare method can determine which items to sort.

Changes to a form

In general, to switch between ascending and descending sort, you click the column heading more than once. Users expect that if they click a column heading, the sort will occur, and then clicking again will change the sort order. The preceding code example needs to be able to determine when to click a column more than once. To do this, you can add a private integer variable to the Form class. This variable stores the column that was last clicked. The Columnclick event-handling method uses this variable to compare the last column with the currently clicked column and to determine whether they are the same. Add the following member definitions to the Form class.

' Visual Basic

Dim SortColumn as Integer =-1

C#

private int sortcolumn =-1;

Columnclick Event-handling method changes

The Columnclick event-handling method defined in the previous example needs to be modified to keep track of the columns that have been clicked and the current sort order. Add the following code to replace the code in the Columnclick event-handling method created in the previous example.

' Visual Basic

Private Sub Listview1_columnclick (sender as Object, E as

System.Windows.Forms.ColumnClickEventArgs)

' Determine whether the ' same as the last column clicked.

If e.column <> SortColumn Then

' Set the sort column to the new column.

SortColumn = E.column

' Set the sort order to ascending by default.

listview1.sorting = SortOrder.Ascending

Else

' Determine what ' the last sort order is and change it.

If listview1.sorting = sortorder.ascending Then

listview1.sorting = sortorder.descending

Else

listview1.sorting = SortOrder.Ascending

End If

End If

' Call the ' sort method to manually sort.

Listview1.sort ()

' Set the Listviewitemsorter ' to a new listviewitemcomparer

' Object.

Listview1.listviewitemsorter = New ListViewItemComparer (E.column, _

listview1.sorting)

End Sub

C#

private void Listview1_columnclick (object sender,

System.Windows.Forms.ColumnClickEventArgs e)

{

Determine whether the column is the same as the last column clicked.

if (E.column!= sortcolumn)

{

Set the sort column to the new column.

SortColumn = E.column;

Set the sort order to ascending by default.

listview1.sorting = sortorder.ascending;

}

Else

{

Determine what the last sort order is it.

if (listview1.sorting = = sortorder.ascending)

listview1.sorting = sortorder.descending;

Else

listview1.sorting = sortorder.ascending;

}

Call the Sort method to manually sort.

Listview1.sort ();

Set the Listviewitemsorter property to a new ListViewItemComparer

Object.

This.listView1.ListViewItemSorter = new ListViewItemComparer (E.column,

listview1.sorting);

}

The code adds some logic before setting the Listviewitemsorter property and calling the Sort method. The increased code determines whether the currently clicked item is the same as the one that was last clicked. If different, the SortColumn variable is set and the SortOrder.Ascending value is assigned to the sorting property. If the SortColumn variable is the same as the column currently clicked, the sorting property is changed to the reverse sort order. In this example, the sorting property is used as a method for defining the sort order of the items. Because you are using a custom comparer class to sort items, setting the sorting property has no effect on the sort operation. In this example, it is simply used as a variable.

After you specify a sort order, the only other change to the Columnclick event-handling method code is to add additional parameter values to the ListViewItemComparer object's creation, which is the object that you want to assign to the Listviewitemsorter property. As the following section of this example shows, the ListViewItemComparer class contains a new parameter that specifies the sort order. You use the value of the Listview.sorting property to assign a value to the parameter.

Changes to the ListViewItemComparer class

The previous series of changes that enable the example to be sorted in ascending or descending order is the change to the ListViewItemComparer class. The added code will perform the logic required to compare the project in one of two sort modes. Add the following code to replace the code defined for ListViewItemComparer in the previous example.

' Visual Basic

' Implements the manual sorting of items by columns.

Class ListViewItemComparer

Implements IComparer

Private Col as Integer

Private Order as SortOrder



Public Sub New ()

Col = 0

Order = SortOrder.Ascending

End Sub



Public Sub New (column as Integer, order as SortOrder)

col = column

Me.order = Order

End Sub



Public Function Compare (x As Object, y as Object) as Integer _

Implements System.Collections.IComparer.Compare

Dim ReturnVal as Integer =-1

ReturnVal = [String]. Compare (CType (x, _

ListViewItem). SubItems (COL). Text, _

CType (y, ListViewItem). SubItems (COL). Text)

' Determine whether the sort order is descending.

If order = sortorder.descending Then

' Invert the value returned by String.Compare.

ReturnVal *=-1

End If

Return ReturnVal

End Function

End Class

C#

Implements the manual sorting of items by columns.

Class Listviewitemcomparer:icomparer {

private int col;

private SortOrder order;

Public ListViewItemComparer () {

col=0;

order = sortorder.ascending;

}

public listviewitemcomparer (int column, SortOrder order)

{

Col=column;

This.order = order;

}

public int Compare (object x, Object y)

{

int returnval=-1;

ReturnVal = String.Compare ((listviewitem) x). Subitems[col]. Text,

((ListViewItem) y). Subitems[col]. Text);

Determine whether the sort order is descending.

if (order = = sortorder.descending)

Invert the value returned by String.Compare.

ReturnVal *=-1

return returnval;

}

}33

The code adds a sort order parameter to the constructor and creates a private variable to store the value. The code for the Compare method has been changed to determine whether the sort order is descending. If so, multiply the return value of the String.Compare method by 1 To change the value so that the value returned by the Compare method is the opposite of the value returned by the String.Compare.

Run the code and click the column. The column is arranged in ascending order. When you click the same column, the columns are sorted in descending order. Similarly, the date column does not have the correct sort because it is stored as a string instead of a date. In the next section, you complete the example by adding functionality to sort by date or by string (depending on the type of data).

Sort Date

The data that is placed in the ListView control as a project is displayed as text and stored as text. This makes sorting using the String.Compare method in the IComparer class to be very simple. String.Compare can sort alphabetic characters and numbers. However, you cannot use String.Compare to correctly sort specific data types, such as date and time information. Therefore, the System.DateTime structure has a Compare method that acts like a String. This method can be used to perform the same type of sorting based on chronological order. In this section, you only need to modify the Compare method to sort the dates correctly.

Add the following code to replace the code defined by the Compare method, which is the method of the ListViewItemComparer class defined in the previous example.

' Visual Basic

Public Function Compare (ByVal x As Object, ByVal y as Object) as

Integer Implements System.Collections.IComparer.Compare

Dim ReturnVal as Integer

' Determine whether the type being compared is a date type.

Try

' Parse the two objects passed as a parameter as a DateTime.

Dim firstdate as System.DateTime = DateTime.Parse (CType (x, _

ListViewItem). SubItems (COL). Text)

Dim seconddate as System.DateTime = DateTime.Parse (CType (Y, _

ListViewItem). SubItems (COL). Text)

' Compare the two dates.

ReturnVal = Datetime.compare (firstdate, Seconddate)

' If neither compared object has a valid date format,

' Compare as a string.

Catch

' Compare the two items as a string.

ReturnVal = [String]. Compare (CType (x, _

ListViewItem). SubItems (COL). Text, CType (Y,listviewitem). SubItems (COL). Text)

End Try



' Determine whether the sort order is descending.

If order = sortorder.descending Then

' Invert the value returned by String.Compare.

ReturnVal *=-1

End If

Return ReturnVal

End Function

C#

public int Compare (object x, Object y)

{

int returnval;

Determine whether the type being compared is a date type.

Try

{

Parse the two objects passed as a parameter as a DateTime.

System.DateTime firstdate =

DateTime.Parse (((ListViewItem) x). Subitems[col]. Text);

System.DateTime seconddate =

DateTime.Parse (((ListViewItem) y). Subitems[col]. Text);

Compare the two dates.

ReturnVal = Datetime.compare (firstdate, seconddate);

}

If neither compared object has a valid date format, compare

As a string.

Catch

{

Compare the two items as a string.

ReturnVal = String.Compare ((listviewitem) x). Subitems[col]. Text,

((ListViewItem) y). Subitems[col]. Text);

}

Determine whether the sort order is descending.

if (order = = sortorder.descending)

Invert the value returned by String.Compare.

ReturnVal *=-1;

return returnval;

}

Start the code that has been added to replace the earlier version of the Compare method by depositing the x and Y parameters into a DateTime object. This excerpt is executed in a try/catch block to catch possible exceptions by forcing two of the objects being compared into a DateTime object. If an exception occurs, it signals that the type that the code is converting is an invalid date or time and can be sorted using the String.Compare method. If all two types are dates, they are sorted using the Datetime.compare method.

Run this new version of the sample code and click any column. You will notice that they correctly sort the subprojects, including the date columns. The ListView control in the example now correctly handles all of the data types it displays.

Summary

The ListView control can provide the ability to display data in a variety of ways. It can be used to display individual items or to display items that contain subproject information. Using the sort functionality provided by the ListView control, you can also enable users to sort items in ListView controls based on those subprojects, regardless of the type of data that appears. This ability to sort projects and their subprojects enables your application to demonstrate its behavior in a manner familiar to users of Microsoft®windows®explorer and other applications, providing the ability to display and sort their content ListView data.




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.