Results 1 to 10 of 10

Thread: FYI: Sort ListView - Another Way of Doing It

  1. #1

    Thread Starter
    Frenzied Member circuits2's Avatar
    Join Date
    Sep 2006
    Location
    Kansas City, MO
    Posts
    1,027

    Lightbulb FYI: Sort ListView - Another Way of Doing It

    I have seen many posts where someone wanted to sort a ListView by a column other than the first. MSDN and some of the more seasoned developers in this forum lead you down the IComparer route, which is probably the best practice. However, not all situations warrant the sometimes lengthy code of the "best practice". The code below is a method I use for sorting ListViews in smaller applications. If you remove my comments then you can see that sorting can be achieved in as little as 20-30 lines of code.


    Code:
    ' I created this structure to represent one item in the ListView.
        ' You do not have to create a structure, you can simply use individual variables.
        ' My ListView has 4 columns: Component, UsedOn, Production, and Rank.
        Public Structure ItemInList
            Dim Component As String
            Dim UsedOn As String
            Dim Production As String
            Dim Rank As String
        End Structure
    
    
        ' Here I have created a sub for the sorting procedure. You can call this sub
        ' from the ColumnHeader.Click() event in the ListView.
        Private Sub SortListViewByRankColumn()
    
            Dim relocate As ItemInList  'This will be the current item we are looking at.
            Dim itemsMoved As Boolean   'This will tell us if we made any changes to order.
            Dim index As Integer        'This is the index of the current ListView item.
    
            ' The outside Do loop makes sure we keep moving things around until we
            ' arrive at the order we want.
            Do
                ' itemsMoved is a boolean that we set to True if we make any changes to the
                ' order of the ListView.
                itemsMoved = False
    
                ' The inside For loop is the main gear. The column in my ListView that I am
                ' sorting by contains numbers. So I can choose whether I want to sort in
                ' Ascending or Descending order, or I can let the user choose. If your column
                ' does not contain letters, then you can simply use the ASCII values of the
                ' first letter, and then refine your order by sorting by the second and then
                ' third letter for all items that start with the same first letter.
                For index = 0 To (Me.ListView1.Items.Count - 2)
    
                    ' The number in the fourth column of my ListView is formatted to two
                    ' decimal places. So here I compare the first item to the second item.
                    ' I am sorting in Descending order, so if the first item is less than
                    ' the second item, then I move it to the bottom of the list.
                    ' If you want to sort in Ascending order, then change this to see if
                    ' the first item is greater than the second item.
                    If Double.Parse(Me.ListView1.Items.Item(index).SubItems(3).Text) < _
                    Double.Parse(Me.ListView1.Items.Item(index + 1).SubItems(3).Text) Then
    
                        ' If the item is lower than the item below it, then save it's values
                        ' into the relocate variable.
                        relocate.Component = Me.ListView1.Items.Item(index).SubItems(0).Text()
                        relocate.UsedOn = Me.ListView1.Items.Item(index).SubItems(1).Text()
                        relocate.Production = Me.ListView1.Items.Item(index).SubItems(2).Text()
                        relocate.Rank = Me.ListView1.Items.Item(index).SubItems(3).Text()
    
                        ' Now remove that item from the list. This moves the rest of the items
                        ' in the list up one.
                        Me.ListView1.Items.Item(index).Remove()
    
                        ' Now create a new ListViewItem, it will be added as the last item
                        ' in the list; which is where we want it.
                        Dim newItem As New ListViewItem
    
                        ' Use the values that you saved from the item you deleted to add the
                        ' new item.
                        newItem = Me.ListView1.Items.Add(relocate.Component)
                        newItem.SubItems.Add(relocate.UsedOn)
                        newItem.SubItems.Add(relocate.Production)
                        newItem.SubItems.Add(relocate.Rank)
    
                        ' Make sure you set your itemsMoved variable to True. This makes sure
                        ' we keep looping through this process until no more changes need to
                        ' be made.
                        itemsMoved = True
    
                    End If
    
                Next index
    
                ' When we have made no changes throughout the inner loop, we are done.
            Loop Until itemsMoved = False
    
        End Sub
    Show the love! Click (rate this post) under my name if I was helpful.

    My CodeBank Submissions: How to create a User Control | Move a form between Multiple Monitors (Screens) | Remove the MDI Client Border | Using Report Viewer with Visual Studio 2012 Express

  2. #2
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: FYI: Sort ListView - Another Way of Doing It

    no disrespect to your code, but making a comparer for use to sort a listview is not lengthy code... probably about 20-30 lines

  3. #3

    Thread Starter
    Frenzied Member circuits2's Avatar
    Join Date
    Sep 2006
    Location
    Kansas City, MO
    Posts
    1,027

    Re: FYI: Sort ListView - Another Way of Doing It

    I agree. I noted that it is sometimes lengthy depending on the specific situation. My method is targeted more towards beginners who are not quite ready to take the IComparer route.
    Show the love! Click (rate this post) under my name if I was helpful.

    My CodeBank Submissions: How to create a User Control | Move a form between Multiple Monitors (Screens) | Remove the MDI Client Border | Using Report Viewer with Visual Studio 2012 Express

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: FYI: Sort ListView - Another Way of Doing It

    Creating an IComparer for sorting a ListView is only lengthy if you have many columns containing data of different types, thus each column must be compared in a different way. Using a method other than an IComparer is going to become lengthy in those situations too. I don't doubt that your code does what it's supposed to but I don't think it's necessarily any quicker to code than creating an IComparer, or easier if you grasp the concept of implementing an interface. Creating your own IComparer is also a good chance to learn some OO principles if you don't already know how to implement an interface.

    You should also ask a Mod to move this thread to the VB.NET CodeBank.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Frenzied Member circuits2's Avatar
    Join Date
    Sep 2006
    Location
    Kansas City, MO
    Posts
    1,027

    Re: FYI: Sort ListView - Another Way of Doing It

    What's the CodeBank?
    Show the love! Click (rate this post) under my name if I was helpful.

    My CodeBank Submissions: How to create a User Control | Move a form between Multiple Monitors (Screens) | Remove the MDI Client Border | Using Report Viewer with Visual Studio 2012 Express

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: FYI: Sort ListView - Another Way of Doing It

    Take a look down the list of forums on the front page of the site.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  7. #7
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,709

    Re: FYI: Sort ListView - Another Way of Doing It

    Here is the shortest you can get.
    VB Code:
    1. ' Implements the manual sorting of items by index.
    2. Friend Class ListViewItemComparer
    3.     Implements IComparer
    4.  
    5.     Private ind As Integer
    6.  
    7.     Public Sub New()
    8.         ind = 0
    9.     End Sub
    10.  
    11.     Public Sub New(ByVal index As Integer)
    12.         ind = index
    13.     End Sub
    14.  
    15.     Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
    16.        Implements IComparer.Compare
    17.         Return [String].Compare(CType(x, ListViewItem).Index.ToString, CType(y, ListViewItem).Index.ToString)
    18.     End Function
    19. End Class

    Usage based on the first item but can be changed to a selected item or column etc.:
    VB Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.     Dim lvwItm As ListViewItem
    3.     lvwItm = DirectCast(Me.ListView1.Items(1).Clone, ListViewItem)
    4.     Me.ListView1.ListViewItemSorter = New ListViewItemComparer(lvwItm.Index)
    5.     lvwItm = Nothing
    6. End Sub
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6

  8. #8
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,709

    Re: FYI: Sort ListView - Another Way of Doing It

    and a more advanced example by kleinma - http://www.vbforums.com/showpost.php...0&postcount=15
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6

  9. #9

    Thread Starter
    Frenzied Member circuits2's Avatar
    Join Date
    Sep 2006
    Location
    Kansas City, MO
    Posts
    1,027

    Re: FYI: Sort ListView - Another Way of Doing It

    So is it possible to add my code to the CodeBank? It's targeted more towards beginners who are not quite ready to learn the IComparer class.
    Show the love! Click (rate this post) under my name if I was helpful.

    My CodeBank Submissions: How to create a User Control | Move a form between Multiple Monitors (Screens) | Remove the MDI Client Border | Using Report Viewer with Visual Studio 2012 Express

  10. #10
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: FYI: Sort ListView - Another Way of Doing It

    Quote Originally Posted by RobDog888
    and a more advanced example by kleinma - http://www.vbforums.com/showpost.php...0&postcount=15
    yeah that works pretty well. I need to clean that up a bit one day, I could probably make it more efficient.


    Ok. Moved to codebank.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width