MFC List Control: How to correctly delete items from a CListCtrl?

Q: How to correctly delete items from a CListCtrl?

A: Unlike the 'HTREEITEM' values returned from 'CTreeCtrl::InsertItem()', the integer values returned from 'CListCtrl::InsertItem()' aren't stable. In short, this means that you shouldn't store them anywhere. If you need to find an entry again, it's probably best to simply put something useful in 'LVITEM::lParam', and search for it using 'CListCtrl::GetNextItem()'.

Having said that, one can use the following piece of code to correctly delete items from a CListCtrl:

for (int nItem = 0; nItem < m_List.GetItemCount(); )
{
if (m_List.GetItemState(nItem, LVIS_SELECTED) == LVIS_SELECTED)
m_List.DeleteItem(nItem)
;
else
++nItem;
}

Note: Most of the material in this article is taken from codeguru.com


Recommended Reading :





Personal Loans - Loans - Debt Consolidation - Credit Counseling