在MFC列表视图控件框中一次删除多个选中的项目

时间:2015-12-27 11:10:58

标签: listview mfc

我有一个带有扩展样式LVS_EX_CHECKBOXES的MFC listview控件框。用于从列表视图控件框中删除已检查项目的“删除”按钮处理程序代码如下所示:

for (int i = 0; i < m_cList.GetItemCount(); i++)
{    
     // checking for checked items
     BOOL bCheck = m_cList.GetCheck(i);

     if (bCheck != 0)
     {  
         //deleting the  checked items      
         m_cList.DeleteItem(i);
     }
}

我的代码问题是,当我点击删除按钮时,它不会一次删除所有选中的项目。而是一次从列表视图控件框中删除一个项目。因此,如果我想删除多个选中的项目,我需要再次单击“删除”按钮。任何人都可以帮我单击删除按钮一次删除多个项目。

提前谢谢你!

1 个答案:

答案 0 :(得分:1)

问题是DeleteItem函数正在更改项的索引,因此在删除第一项后,索引i在循环内不再有效。 一个好的解决方案是以相反的顺序迭代项目:

for (int i = m_cList.GetItemCount()-1; i>=0; i--)
    {
        // checking for checked items
        BOOL bCheck = m_cList.GetCheck(i);

        if (bCheck != 0)
        {
            //deleting the  checked items      
            m_cList.DeleteItem(i);
        }
    }
相关问题