如ListBox的内容如下,蓝色代表选中的内容
列表 | 索引 | 删除时索引 |
item1 | 0 | 0 |
item2 | 1 | 0 |
item3 | 2 | |
item4 | 3 | 1 |
删除所有选中列:
void CListBox::_DeletSelectedItem() { CArray<int,int> ar; int nCount = CListBox::GetSelCount(); ar.SetSize(nCount); if (CListBox::GetSelItems(nCount,ar.GetData())==LB_ERR) return; for (int i=0; i<nCount; i++){ ItemData* rf = (ItemData*)(CListBox::GetItemData(ar[i]-i)); if (rf != NULL) delete rf; CListBox::SetItemData(ar[i]-i,0); CListBox::DeleteString(ar[i]-i); } }
ar数组是存储选中内容的索引,CListBox::DeleteString(INT nItem)删除的机制是从0往后删除每删除一项所有列的索引减一。故要得到正确的索引应为(ar[i]-i)