Results 1 to 3 of 3

Thread: [RESOLVED] Sort Listview by checkbox state

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Nov 2005
    Posts
    1,834

    Resolved [RESOLVED] Sort Listview by checkbox state

    Does anybody know how to sort a Listview by checkbox state, so all checked items are at the top of the list.

    I'm targeting Framework 2.0.

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

    Re: Sort Listview by checkbox state

    Sorting a ListView is the same regardless. In all the examples you will have already found by searching the web, you will have seen that you need to create an object that implements IComparer to compare two ListViewItems. You can compare them any way you want, including by their Checked properties.
    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

  3. #3

    Thread Starter
    Frenzied Member
    Join Date
    Nov 2005
    Posts
    1,834

    Re: Sort Listview by checkbox state

    Thanks. I didn't know I could use it to compare the Checked property as well.

    vb.net Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.     ListView.ListViewItemSorter = New ListViewCompareChecked(SortOrder.Descending)
    3.     ListView.Sort()
    4. End Sub
    5.  
    6. Public Class ListViewCompareChecked
    7.     Implements IComparer
    8.  
    9.     Private m_SortOrder As SortOrder
    10.  
    11.     Public Sub New(ByVal sort_order As SortOrder)
    12.         m_SortOrder = sort_order
    13.     End Sub
    14.  
    15.     Public Function Compare(ByVal x As Object, ByVal y As Object) _
    16.      As Integer Implements System.Collections.IComparer.Compare
    17.  
    18.         Dim item_x As ListViewItem = DirectCast(x, ListViewItem)
    19.         Dim item_y As ListViewItem = DirectCast(y, ListViewItem)
    20.  
    21.         If m_SortOrder = SortOrder.Ascending Then
    22.             Return item_x.Checked.CompareTo(item_y.Checked)
    23.         Else
    24.             Return -item_x.Checked.CompareTo(item_y.Checked)
    25.         End If
    26.     End Function
    27. End Class
    Last edited by Chris001; Aug 25th, 2011 at 11:38 AM.

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