Geeks With Blogs

David Madden Mastering the craft one mountain at a time.
I have a ListView that is holding session dates for sessions someone may attend.  I like to use a MonthCalendar control to allow the user to select several dates, allowing the control's DateSelected event to add an entry to the ListView control as a formatted date string for readability.  Sorting is not nice though using the plain sort orders.

So I implemented an nice solution.  I added a custom comparer to sort those string dates in the ListView control.  Just add the following to your form's namespace, in my case it was the Sessions form called "frmSessions".
    class SessionDatesListViewItemComparer : IComparer
        private int col;
        public SessionDatesListViewItemComparer()
            col = 0;

        public int Compare(object x, object y)
            int returnVal = -1;
            DateTime dateX = Convert.ToDateTime(((ListViewItem)x).SubItems[col].Text);
            DateTime dateY = Convert.ToDateTime(((ListViewItem)y).SubItems[col].Text);

            returnVal = DateTime.Compare(dateX, dateY);
            return returnVal;
This allowed me to add a the following line in my form's Constructor (you might have more than one).
    this.listView_SessionDates.ListViewItemSorter = new SessionDatesListViewItemComparer();
Now the ListView control sorts nicely each time a date is added.
Posted on Tuesday, April 30, 2013 4:29 PM | Back to top

Comments on this post: Why the custom comparer is your friend

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © DavidMadden | Powered by: