Use VB.NET to sort the ListView project by column of Windows Form

xiaoxiao2021-03-06  46

Use Windows Form to sort the listView project by column

Summary: Description How to provide item sorting based on the listed column column in Microsoft .NET.

Introduction

The ListView control is a very good way to display file system information and display XML or database data. ListView controls are typically used to display graphical icons that represent projects and project text. In addition, the ListView control can also be used to display additional information about items in subprojects. For example, if a ListView control displays a list file, you can configure a listView control to display details such as file size and properties as subprojects. To display sub-project information in the ListView control, you must set the View property to View.Details. In addition, you must create a ColumnHeader object and assign these objects to the columns properties of the ListView control. After setting these properties, the item is displayed in row and column format, similar to the DataGrid control. The ability to display items in this way makes the ListView control provides fast and easy solutions for display data from any type of data source.

Sorting the ListView control is provided by using the sorting attribute of listview. This allows you to define the sort type to be applied to the project. If you just want to sort by project, this is a very good feature. If you are sorted by sub-project, you must use the custom sorting function of the ListView control. This article will show how to perform custom sorting in the ListView control, and how special data type conditions are handled in sorting.

Custom Sorting Features of ListView Controls

The ListView control provides you can use the sorting features instead of being provided by the sorting property. When the ListView control is sorted by the Sorting property, it uses a class that implements the System.collections.icomparer interface. This class provides the sorting function for sorting each item. To sort by sub-projects, you must create your own classes to implement the iComparer interface that can be sorted by the ListView control in turn. This class uses a constructor to define that the constructor can specify the column used by the ListView control sort. After you create this class (usually used as a form of nested classes), you can create an instance of this class and assign it to the listview of the listview. When calling the Sort method, this will determine the custom sort class that the ListView control will be used. The Sort method performs the actual sort of the ListView project.

Ascending order

The basic example provided below illustrates the sorting of its subjects in the ListView control. This example illustrates items in an ascending order list of the ListView control. Ascending ordering or description sequencing will be described later in this article. The goal here is to explain the basic requirements for custom sorting in the ListView control.

Initialization control

If you want to start, create an instance of a ListView control and add it to the form. After the control is on the form, add the item to the ListView control using the items property. You can add any more items, just make sure that the text of each item is unique. Add two subpredals to each item when you create a project. The first sub-project should include digital information, the second sub-project contains date information. The following table example shows how this information may be displayed in the ListView control.

project

Subject 1

Subject 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 into the columns properties of the ListView control. Set the View property to View.Details.

Handling the ColumnClick event To determine which subject set is sorted, you need to know when users click on a column header of a sub-project. To do this, you need to create an event handler method for the listView's ColumnClick event. Event processing methods as a member in the form and make sure it contains the signature displayed by 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 processing method to the ListView control by adding a code to the form of a function, as shown in the example below.

'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 processing method for the ColumnClick event.

'Visual Basic

'Set the listviewitemsorter property 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.

THISTVIEW1.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 attribute of the ListView control, and then assign the columns to click. The clicked column is passed as the component of the event parameter. After setting the ListViewItemSORTER attribute, call the Sort method to perform manual sorting.

Create a ListViewItemComparer class

As mentioned earlier, the key to custom sorting in the ListView control is to create classes that implement the System.Collections.icomparer interface. That is, this class provides sorting. For this example, classes named ListViewItemComparer are defined and added to the nested class of the form. ListViewItemComparer executes the basic ascending order of the specified column passed to its constructor. Add the following class definition to the FORM class and make sure it is correct in the form.

'Visual Basic

'Implements The Manual Sorting of items by column.

Class ListViewItemComparer

Implements iComparerPrivate col Asin

Public Sub New ()

COL = 0

End Sub

Public Sub New (Column As Integer)

COL = Column

End Sub

Public Function Compare (X as Object, Y ask Object) AS INTEGER _

Implements system.collections.icomparer.compare

DIM RETURNVAL AS INTEGER = -1

Returnval = [String] .compare (CType (x, _

ListviewItem). Subitems (color) .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 co1;

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;

}

}

Sort by a necessary method of IComparer interface named compare. This method will use two objects as a parameter, and the parameters will contain two items to be compared. When the Sort method is called in the ColumnClick event processing method of the ListView Control, the sort method uses the ListViewItemComparer object that has been defined and assigned to the ListViewItemsRer property, and calls its Compare method. After creating a ListViewItemComparer object, assign the index of the column that is clicked. The index of this column is used to access sub-items from columns needed to be sorted. Then, the sub-item is passed to the String.Compare method, which compares the item and returns one of three results. If the item in the X parameter is less than the item in the Y parameter, it returns a value of less than zero. If the 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, it returns a value greater than zero. The value returned by the COMPARE method is passed back to the Sort method, which determines that each item being compared is in the list. The Sort method can call the COMPARE method multiple times based on the need to sort all subplices in the selected column.

The previous example is completed. If you run the example and click the column header of the ListView control, the project will be properly sorted in alphabetical order or digital order. The only column that cannot be properly sorted is a column containing date information. This article will be introduced later. Sorting date columns.

This example illustrates the basic elements required to perform basic manual project sorts in the ListView control. The next section will expand this example, provide ascending order and descending ordering.

Sorting or descending order

Users of the ListView control will expect to have functions that are simultaneously sorted in ascending order and descending order. To achieve this feature, some modifications are required to make the COMPARE method to determine the items to be sorted.

To change the form of the form, you want to switch between ascending and descending order, you have to click the column title multiple times. User expects if they click on column headings, sorting will happen, and then click again to change the order sequence. The previous code example needs to be able to determine when a column is multiple times. To do this, you can add a private integer variable to the FORM class. This variable stores the column of the last click. The ColumnClick event processing method will use this variable to compare the previous columns and the current click columns and make sure they are the same. Add the following member definition to the FORM class.

'Visual Basic

DIM Sortcolumn as integer = -1

// c #

PRIVATE INT SORTCOLUMN = -1;

Change of COLUMNCLICK Event Handling Method

The ColumnClick event processing method defined in the previous example needs to be modified to track the clicked column and the current sort order. Add the following code to replace the code in the ColumnClick event processing method created in the previous example.

'Visual Basic

Private Sub ListView1_ColumnClick (Sender As Object, E AS

System.windows.Forms.columnClicKeventargs)

'DETERMINE WHETER THE Column Is The Same as The Last Column Clicked.

IF E.COLUMN <> SortColumn Then

'Set the sort column to the new color.

Sortcolumn = E.COLUMN

'Set the sort order to ask ascending by default.

Listview1.sorting = sortorder.ascending

Else

'DETERMINE What The Last Sort ORDER WAS AND CHANGE IT.

If listview1.sorting = sortorder.ascending thein

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 property 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 color.

Sortcolumn = E.COLUMN;

// set the sort order to ask ascending by Default.

Listview1.sorting = sortorder.ascending;

}

Else

{

// DETERMINE What The Last Sort ORDER WAS AND CHANGE 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.

THISTVIEW1.ListViewItemsORTER = New ListViewItemComparer (E.COLUMN,

Listview1.sorting;

}

This code adds some logic before setting the listViewItemsORTER attribute and call the Sort method. The increased code determines whether the currently clicked item is the same as the column that is already clicked last time. If you do different, the SortColumn variable will be 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 will change to the opposite sort order. In this example, the Sorting property is used as a method for defining the order of the project. Because you use a custom comparison program class to sort your project, you have no effect on the sorting operation. In this example, it is just simply as a variable.

After specifying the order sequence, the only other changes to the ColumnClick event processing method code are to add additional parameter values ​​to the creation of the ListViewItemComparer object, and the object is an object you want to assign to the ListViewItemsORTER property. As shown in this example, the ListViewItemComparer class contains a new parameter for specifying the order sequence. You use the value of the listview.sorting attribute to assign the value to this parameter.

Change of ListViewItemComparer class

This example can be sorted on ascending or descending order is a change to the ListViewItemComparer class. The increased code will perform the logic required to compare the items in two sort modes. Add the following code to replace the code defined by the 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 ask Object) AS INTEGER _

Implements system.collections.icomparer.compare

DIM RETURNVAL AS INTEGER = -1

Returnval = [String] .compare (CType (x, _

ListviewItem). Subitems (color) .text, _cType (y, listviewitem). Subitems (color) .text)

'DETERMINE WHETER 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 #

//Mplements the manual sorting of items by columns.

Class ListViewItemComparer: iComparer {

Private int co1;

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

This code adds the sort order parameter to the constructor and creates a private variable for storing the value. The code of the COMPARE method has changed to determine if the sort order is descending. If so, multiply the return value of the String.Compare method with -1 to change the value, so that the value returned by the COMPARE method is opposite to the value returned by String.Compare.

Run the code and click the column. This column is arranged in an ascending order. Click the same column, the column will be sorted in sequence. Similarly, the date column is not properly sorted because it is stored as a string instead of date. In the next section, the example is completed by adding a function or by a string (depending on the type of data) to complete the example.

Sort date

As a project, the data placed in the listView control is displayed as text and stored in the form of text. This makes sorting using the String.Compare method in the IComparer class. String.comPare can be sorted alphanumeric characters and numbers. However, using string.compare cannot be properly sorted, such as dates and time information. Therefore, the System.DateTime structure has a COMPARE method that is the same as the STRING class. This method can be used to perform the sorting of the same type based on the time order. In this section, you only need to modify the Compare method to properly sort the date.

The following code is added to the COMPARE method (the method is the code defined by the method of the ListViewItemComparer class defined in the previous example).

'Visual BasicPublic Function Compare (Byval x as object, byval y as object) AS

Integer Implements System.collections.icomparer.comPare

DIM RETURNVAL AS INTEGER

'DETERMINE WHENER 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, secondddate)

'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 WHETER 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 secondddddate =

DateTime.Parse ((ListViewItem) Y). Subitems [col] .text);

// ComPare the two dates.

Returnval = datetime.compare (firstdate, seconddddate);

}

// 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;

}

Starting the code that has been added to replace the earlier version of the COMPARE method is activated by storing the X and Y parameters to the DateTime object. This excerpt is executed in the TRY / CATCH block by mandatory to store two objects to the DateTime object. If an exception occurs, it sends a signal to notify the code to be converted. The type of invalid date or time can be sorted using the string.Compare method. If both types are dates, they use the DateTime.Compare method for sorting.

This new version of this sample code is run, and click any column. You will notice they correctly sequence sub-projects, including date columns. Now, the ListView control in this example can process all the data types it displayed.

summary

The ListView control is capable of displaying data in a variety of ways. It can be used to display a separate item or display a project containing sub-item information. Using the sorting feature provided by the ListView control, you can also enable users based on items in the sub-project sorting ListView control, without considering the data types. This ability to sort the project and its subproject enable your application to express its behavior in the manner familiar to Microsoft® Windows® Explorer and other applications, they provide data ListView's ability to display and sort their content. .

转载请注明原文地址:https://www.9cbs.com/read-65923.html

New Post(0)