473,748 Members | 4,804 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sorting ListView Columns

Is there a way to sort by a specified column in a listview? I'd like my users to be able to click on the column heading and have the listview sort by that column.

Thanks,

Billyb
Nov 20 '05 #1
5 7279
Class ListViewItemCom parer
Implements IComparer

Private col As Integer
Public Sub New()
col = 0
End Sub
Public Sub New(ByVal column As Integer)
col = column
End Sub

Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compa re
Return [String].Compare(CType( x, ListViewItem).S ubItems(col).Te xt, CType(y, ListViewItem).S ubItems(col).Te xt)
End Function

End Class
Public Sub ColumnClick(ByV al sender As Object, ByVal e As ColumnClickEven tArgs) Handles listNumberList. ColumnClick

Me.listNumberLi st.ListViewItem Sorter = New ListViewItemCom parer(e.Column)

End Sub
"billuy" wrote:
Is there a way to sort by a specified column in a listview? I'd like my users to be able to click on the column heading and have the listview sort by that column.

Thanks,

Billyb

Nov 20 '05 #2
* =?Utf-8?B?R2xlbm4gV2l sc29u?= <Gl*********@di scussions.micro soft.com> scripsit:
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compa re
Return [String].Compare(CType( x, ListViewItem).S ubItems(col).Te xt, CType(y, ListViewItem).S ubItems(col).Te xt)


Why do you use '[...]' around 'String'?!

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>
Nov 20 '05 #3
To take it one step further (this allows you to sort strings, dates and
numbers columns appropriately) Don't think I ever finished the
enumSortType.Da teSort code completely... Not sure.

HTH,
Greg

in your form's class add:

' form level variable
Private lvwColumnSorter 1 As ListViewColumnS orter

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeCompo nent()

'Add any initialization after the InitializeCompo nent() call
' Create an instance of a ListView column sorter and assign it
' to the ListView control.
lvwColumnSorter 1 = New ListViewColumnS orter

Me.lvw.ListView ItemSorter = lvwColumnSorter 1

End Sub

Private Sub lvw_ColumnClick (ByVal sender As Object, ByVal e As
System.Windows. Forms.ColumnCli ckEventArgs) Handles lvw.ColumnClick
Select Case e.Column
Case TheNumericColum n -- sample custom enum for my columns...
lvwColumnSorter 1.SortType =
ListViewColumnS orter.enumSortT ype.NumericSort
Case Else
lvwColumnSorter 1.SortType =
ListViewColumnS orter.enumSortT ype.AlphaSort
End Select

' Determine if the clicked column is already the column that is
' being sorted.
If (e.Column = lvwColumnSorter 1.SortColumn) Then
' Reverse the current sort direction for this column.
If (lvwColumnSorte r1.Order = SortOrder.Ascen ding) Then
lvwColumnSorter 1.Order = SortOrder.Desce nding
Else
lvwColumnSorter 1.Order = SortOrder.Ascen ding
End If
Else
' Set the column number that is to be sorted; default to
ascending.
lvwColumnSorter 1.SortColumn = e.Column
lvwColumnSorter 1.Order = SortOrder.Ascen ding
End If

' Perform the sort with these new sort options.
Me.lvw.Sort()

End Sub

Add this helper class to project:

Imports System.Collecti ons
Imports System.Windows. Forms

Public Class ListViewColumnS orter
Implements System.Collecti ons.IComparer

Private ColumnToSort As Integer
Private OrderOfSort As SortOrder
Private ObjectCompare As CaseInsensitive Comparer
Private TypeOfSort As enumSortType

Enum enumSortType
AlphaSort
NumericSort
DateSort
End Enum

Public Sub New()
' Initialize the column to '0'.
ColumnToSort = 0

' Initialize the sort order to 'none'.
OrderOfSort = SortOrder.None

' Initialize the CaseInsensitive Comparer object.
ObjectCompare = New CaseInsensitive Comparer

' Initialize the default column type to be Alpha.
TypeOfSort = enumSortType.Al phaSort
End Sub

Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer
Implements IComparer.Compa re
Dim compareResult As Integer
Dim listviewX As ListViewItem
Dim listviewY As ListViewItem

' Cast the objects to be compared to ListViewItem objects.
listviewX = CType(x, ListViewItem)
listviewY = CType(y, ListViewItem)

' Compare the two items.
Select Case TypeOfSort
Case enumSortType.Al phaSort, enumSortType.Da teSort
compareResult =
ObjectCompare.C ompare(listview X.SubItems(Colu mnToSort).Text,
listviewY.SubIt ems(ColumnToSor t).Text)

Case enumSortType.Nu mericSort
Dim intx As Integer =
CInt(listviewX. SubItems(Column ToSort).Text)
Dim inty As Integer =
CInt(listviewY. SubItems(Column ToSort).Text)

If intx = inty Then
compareResult = 0
ElseIf intx > inty Then
compareResult = 1
Else
compareResult = -1
End If
End Select
' Calculate the correct return value based on the object
' comparison.
If (OrderOfSort = SortOrder.Ascen ding) Then
' Ascending sort is selected, return typical result of
' compare operation.
Return compareResult
ElseIf (OrderOfSort = SortOrder.Desce nding) Then
' Descending sort is selected, return negative result of
' compare operation.
Return (-compareResult)
Else
' Return '0' to indicate that they are equal.
Return 0
End If
End Function

Public Property SortColumn() As Integer
Set(ByVal Value As Integer)
ColumnToSort = Value
End Set

Get
Return ColumnToSort
End Get
End Property

Public Property Order() As SortOrder
Set(ByVal Value As SortOrder)
OrderOfSort = Value
End Set

Get
Return OrderOfSort
End Get
End Property

Public Property SortType() As enumSortType
Get
Return TypeOfSort
End Get
Set(ByVal Value As enumSortType)
TypeOfSort = Value
End Set
End Property
End Class
"Glenn Wilson" <Gl*********@di scussions.micro soft.com> wrote in message
news:87******** *************** ***********@mic rosoft.com...
Class ListViewItemCom parer
Implements IComparer

Private col As Integer
Public Sub New()
col = 0
End Sub
Public Sub New(ByVal column As Integer)
col = column
End Sub

Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compa re Return [String].Compare(CType( x, ListViewItem).S ubItems(col).Te xt, CType(y, ListViewItem).S ubItems(col).Te xt) End Function

End Class
Public Sub ColumnClick(ByV al sender As Object, ByVal e As ColumnClickEven tArgs) Handles listNumberList. ColumnClick
Me.listNumberLi st.ListViewItem Sorter = New ListViewItemCom parer(e.Column)

End Sub
"billuy" wrote:
Is there a way to sort by a specified column in a listview? I'd like my users to be able to click on the column heading and have the listview sort
by that column.
Thanks,

Billyb

Nov 20 '05 #4
Thanks to all for the help!

"Greg Burns" wrote:
To take it one step further (this allows you to sort strings, dates and
numbers columns appropriately) Don't think I ever finished the
enumSortType.Da teSort code completely... Not sure.

HTH,
Greg

in your form's class add:

' form level variable
Private lvwColumnSorter 1 As ListViewColumnS orter

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeCompo nent()

'Add any initialization after the InitializeCompo nent() call
' Create an instance of a ListView column sorter and assign it
' to the ListView control.
lvwColumnSorter 1 = New ListViewColumnS orter

Me.lvw.ListView ItemSorter = lvwColumnSorter 1

End Sub

Private Sub lvw_ColumnClick (ByVal sender As Object, ByVal e As
System.Windows. Forms.ColumnCli ckEventArgs) Handles lvw.ColumnClick
Select Case e.Column
Case TheNumericColum n -- sample custom enum for my columns...
lvwColumnSorter 1.SortType =
ListViewColumnS orter.enumSortT ype.NumericSort
Case Else
lvwColumnSorter 1.SortType =
ListViewColumnS orter.enumSortT ype.AlphaSort
End Select

' Determine if the clicked column is already the column that is
' being sorted.
If (e.Column = lvwColumnSorter 1.SortColumn) Then
' Reverse the current sort direction for this column.
If (lvwColumnSorte r1.Order = SortOrder.Ascen ding) Then
lvwColumnSorter 1.Order = SortOrder.Desce nding
Else
lvwColumnSorter 1.Order = SortOrder.Ascen ding
End If
Else
' Set the column number that is to be sorted; default to
ascending.
lvwColumnSorter 1.SortColumn = e.Column
lvwColumnSorter 1.Order = SortOrder.Ascen ding
End If

' Perform the sort with these new sort options.
Me.lvw.Sort()

End Sub

Add this helper class to project:

Imports System.Collecti ons
Imports System.Windows. Forms

Public Class ListViewColumnS orter
Implements System.Collecti ons.IComparer

Private ColumnToSort As Integer
Private OrderOfSort As SortOrder
Private ObjectCompare As CaseInsensitive Comparer
Private TypeOfSort As enumSortType

Enum enumSortType
AlphaSort
NumericSort
DateSort
End Enum

Public Sub New()
' Initialize the column to '0'.
ColumnToSort = 0

' Initialize the sort order to 'none'.
OrderOfSort = SortOrder.None

' Initialize the CaseInsensitive Comparer object.
ObjectCompare = New CaseInsensitive Comparer

' Initialize the default column type to be Alpha.
TypeOfSort = enumSortType.Al phaSort
End Sub

Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer
Implements IComparer.Compa re
Dim compareResult As Integer
Dim listviewX As ListViewItem
Dim listviewY As ListViewItem

' Cast the objects to be compared to ListViewItem objects.
listviewX = CType(x, ListViewItem)
listviewY = CType(y, ListViewItem)

' Compare the two items.
Select Case TypeOfSort
Case enumSortType.Al phaSort, enumSortType.Da teSort
compareResult =
ObjectCompare.C ompare(listview X.SubItems(Colu mnToSort).Text,
listviewY.SubIt ems(ColumnToSor t).Text)

Case enumSortType.Nu mericSort
Dim intx As Integer =
CInt(listviewX. SubItems(Column ToSort).Text)
Dim inty As Integer =
CInt(listviewY. SubItems(Column ToSort).Text)

If intx = inty Then
compareResult = 0
ElseIf intx > inty Then
compareResult = 1
Else
compareResult = -1
End If
End Select
' Calculate the correct return value based on the object
' comparison.
If (OrderOfSort = SortOrder.Ascen ding) Then
' Ascending sort is selected, return typical result of
' compare operation.
Return compareResult
ElseIf (OrderOfSort = SortOrder.Desce nding) Then
' Descending sort is selected, return negative result of
' compare operation.
Return (-compareResult)
Else
' Return '0' to indicate that they are equal.
Return 0
End If
End Function

Public Property SortColumn() As Integer
Set(ByVal Value As Integer)
ColumnToSort = Value
End Set

Get
Return ColumnToSort
End Get
End Property

Public Property Order() As SortOrder
Set(ByVal Value As SortOrder)
OrderOfSort = Value
End Set

Get
Return OrderOfSort
End Get
End Property

Public Property SortType() As enumSortType
Get
Return TypeOfSort
End Get
Set(ByVal Value As enumSortType)
TypeOfSort = Value
End Set
End Property
End Class
"Glenn Wilson" <Gl*********@di scussions.micro soft.com> wrote in message
news:87******** *************** ***********@mic rosoft.com...
Class ListViewItemCom parer
Implements IComparer

Private col As Integer
Public Sub New()
col = 0
End Sub
Public Sub New(ByVal column As Integer)
col = column
End Sub

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

Implements IComparer.Compa re
Return [String].Compare(CType( x, ListViewItem).S ubItems(col).Te xt,

CType(y, ListViewItem).S ubItems(col).Te xt)
End Function

End Class
Public Sub ColumnClick(ByV al sender As Object, ByVal e As

ColumnClickEven tArgs) Handles listNumberList. ColumnClick

Me.listNumberLi st.ListViewItem Sorter = New ListViewItemCom parer(e.Column)

End Sub
"billuy" wrote:
Is there a way to sort by a specified column in a listview? I'd like my users to be able to click on the column heading and have the listview sort
by that column.
Thanks,

Billyb


Nov 20 '05 #5
The contact I got it from is a C# Coder, and I used the converter in VB Resource Kit to convert it.. Sorry Should have taken them out, normally do.

"Herfried K. Wagner [MVP]" wrote:
* =?Utf-8?B?R2xlbm4gV2l sc29u?= <Gl*********@di scussions.micro soft.com> scripsit:
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compa re
Return [String].Compare(CType( x, ListViewItem).S ubItems(col).Te xt, CType(y, ListViewItem).S ubItems(col).Te xt)


Why do you use '[...]' around 'String'?!

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>

Nov 20 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1739
by: rmorvay | last post by:
I have successfully integrated sorting in the listview control with the following code: Private Sub ListView_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles ListView.ColumnClick If ListView.Sorting = System.Windows.Forms.SortOrder.Ascending Then ListView.Sorting = System.Windows.Forms.SortOrder.Descending Else ListView.Sorting = System.Windows.Forms.SortOrder.Ascending
0
1221
by: Abhishek | last post by:
Hi! I am using listview control having 4 columns. I want it to behave in a similar manner as the details view of windows explorer. i.e it should sort on all the columns and all the columns should have the functionality to move horizontally (horizontal order of the columns) for this I am using Listview class . I reffred to MSDN and included a class which implements the System.Collections.IComparer interface that performs the ListViewItem
6
1534
by: ReMEn | last post by:
My question is this: How can I apply some kind of a function to a listview that allows it to sort by both string and numbers whenever a header is clicked? For example: ------------------- INDEX -------------------
19
25465
by: Owen T. Soroke | last post by:
Using VB.NET I have a ListView with several columns. Two columns contain integer values, while the remaining contain string values. I am confused as to how I would provide functionality to sort columns based on the column header the user has clicked in both Ascending and Descending formats.
3
1251
by: Sudheer Kareem | last post by:
Hello All, Can anybody tell me the how to sort a list view in vb.net,I have used a list view in my project and the columns of the list view is dynamically created.if i click on the header of any column i should be able to sort that list view accordingly.Please Help me Thanks and Regards
3
472
by: Curtis | last post by:
I am trying to do a simple sort on a list view.With the listview control the first time I sort on the control it sorts the items but anytime after that it fails to sort. I'm sure this is a simple answer but anyways here is my code any help would be greatly apperciated. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load lvTest.Items.Add("1001") lvTest.Items.Add("5000")...
2
1968
by: yxq | last post by:
Hello, By default, when set the listview's property "Sorting=Descending", the listview will sort the items base on the string in first column(column(0)) while adding items, how to specify listview sort the items base on other columns? Thank you
2
7226
by: jediknight | last post by:
Hi, I have a listview which has columns of text and columns of numerical data. I need to be able to sort these columns into ascending/desending order whenever the user clicks on the column header. The text columns are sorted correctly but the numerical columns seem not to get sorted properly. For example I get the following result when I try to sort a numerical
3
4636
by: =?Utf-8?B?UHVjY2E=?= | last post by:
Hi, I'm using vs2005, .net 2 for C# windows application. One of my column on the Listview control has numericstring. Other columns are sorting correctly except this one. It seems to be sorting the 1st numeric char at the beging of the string. How do I resolve this problem? Thank you? -- Thanks.
0
8991
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8830
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9324
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9247
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4606
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2783
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.