Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

MFC: How to sort CListBox items alphabetically?

677 views
Skip to first unread message

Chris

unread,
Aug 26, 2009, 4:27:02 AM8/26/09
to
I use MFC Visual C++ 4.2.

I have a CListBox and a toggle button( Ascending / Descending sort switch
mode ) on my application.

All the items in the ListBox are CString types.

I want to make so that if I click the button all the CListBox items will be
sorted alphabetically Asc / Desc.

How to do that?

Thank you very much.

Giovanni Dicanio

unread,
Aug 26, 2009, 5:54:13 AM8/26/09
to
Chris ha scritto:

I would suggest you to look a CListBox::CompareItem :

http://msdn.microsoft.com/en-us/library/aa295532(VS.60).aspx

Giovanni

Joseph M. Newcomer

unread,
Aug 30, 2009, 11:18:26 PM8/30/09
to
You have to make it owner-draw, so you can use the CompareItem method. CompareItem will
not work if you have owner draw AND LBS_HASSTRINGS, so you have to put the strings in the
ItemData (which is what will happen if you call AddString to an owner-draw control without
LBS_HASSTRINGS). After that, you are on your own. Note that CompareItem, requires that
the return values be -1, 0, 1, not just generic negative, 0, positive (a gross mis-design)
so you can't juse return the value of strcmp/wcscmp/_tcscmp.

One cheat is to have a member variable which is the "polarity" of the sort: 1 for
ascending (set in the constructor) and -1 for descending. Then all you have to do is
multiply the result you compute by the polarity to get the up/down sort.
joe

Joseph M. Newcomer [MVP]
email: newc...@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm

0 new messages