Tip : Removing selected items from a multiselect List Box
Submitted by date of submission user level
Bulent Ozkir 01/17/2001 Beginner
This one is really tricky. :) You are to remove the selected items in an multiselect/extended style list-box. What happens when you execute the code below;
// CORRECT ? CORRECT
// m_lstComputers is a ListBox variable
int nCount = m_lstComputers.GetSelCount();
CArray
aryListBoxSel.SetSize(nCount);
m_lstComputers.GetSelItems(nCount, aryListBoxSel.GetData());
for(int i = 0; i < nCount ; i++)
{
if (LB_ERR != aryListBoxSel[i])
{
m_lstComputers.GetText(aryListBoxSel[i] , m_strComputer);
m_lstComputers.DeleteString(aryListBoxSel[i] );
}
}
There is a small glitch in this code. Most programmers fall into this trap. When you remove an item from a listbox or combobox, it is recalculated and redrawn. So when you remove an item from n items, in the next attempt you have n-1 items. Look at the GetText and DeleteString functions below in the correct implementation. I subtract - i from iterated items each time. This really works. Magic ? No . Just scrutinize the things...
NOTE : The code segments below also work correctly for single select list boxes... So you have a general function for all kinds now... :)
// CORRECT ? NO
// m_lstComputers is a ListBox variable
int nCount = m_lstComputers.GetSelCount();
CArray
aryListBoxSel.SetSize(nCount);
m_lstComputers.GetSelItems(nCount, aryListBoxSel.GetData());
for(int i = 0; i < nCount ; i++)
{
if (LB_ERR != aryListBoxSel[i])
{
m_lstComputers.GetText(aryListBoxSel[i] - i , m_strComputer);
m_lstComputers.DeleteString(aryListBoxSel[i] - i );
}
}
About the Author:
Bulent Ozkir is a Turkey based senior software engineer. He has worked as a senior support engineer for Microsoft from 1998 to 2000. In his over 5 years programming career he has been working on various programming technologies including VB, VC, Visual Interdev, JavaScript, ASP, HTML/DHTML, WMI, COM+, TCP/IP, IIS, SS3, MCIS25, ASP and SQL Server. His background includes B.A. Comp. Sc., MCSE + Internet and MCSD. See members area for more details.