Getting notified when a list box has an item removed?

492 Views Asked by At

I use CListBox::SetItemData to store a pointer to some data in my ownerdrawn CListBox-derived class, and I'd like the listbox itself to keep track of it and free the memory when its no longer needed.

For that I'd need to be notified each time an item is deleted (including LB_RESETCONTENT and every possible other case where an item is deleted). Is there an event or events that I can handle to achieve that?

4

There are 4 best solutions below

0
On BEST ANSWER

As its owner drawn with one of the LBS_OWNERDRAW* styles you can look out for WM_DELETEITEM;

Sent to the owner of a list box or combo box when the list box or combo box is destroyed or when items are removed by the LB_DELETESTRING, LB_RESETCONTENT, CB_DELETESTRING, or CB_RESETCONTENT message. The system sends a WM_DELETEITEM message for each deleted item

0
On

Since you're subclassing the listbox already anyway, the 'proper' design would (IMO) be to add data management functionality to the listbox, which would then know when items are removed and can delete the data as required. What I mean is, let's say your list keeps track of people, you'd add AddPerson(Person p) and RemovePerson(Person p) methods to your class. The implementation of RemovePerson would remove the respective entry from the list, and delete all data related to it. So don't use CListBox::DeleteString to remove things, use the higher-level API that you implement yourself.

0
On

No. A ListBox only generates notifications for things that the user does. The user cannot remove or add or empty a list box, that can only be done by your own code. So the philosophy here is that the control doesn't have to tell you about something you already know. You can arbitrarily generate your own message in the code that modifies the content. But of course inheriting your own class from CListBox and adding your own virtual methods would be better.

2
On

It's easy - just subclass the list box and add message handlers for LB_DELETESTRING and LB_RESETCONTENT

See here for details:

http://www.codeguru.com/cpp/controls/listbox/article.php/c4759/CListBox-with-the-Horizontal-Scroll-Bar-that-Works.htm