开发者

Remove specific items from a listbox in MFC

开发者 https://www.devze.com 2023-03-11 04:57 出处:网络
CString dance[] = {L\"Atb\", L\"Tiesto\", L\"Madonna\", L\"Paul va开发者_开发技巧n Dyk\", L\"Armin van Burren\", L\"Jennifer Lopez\"};
CString dance[] = {L"Atb", L"Tiesto", L"Madonna", L"Paul va开发者_开发技巧n Dyk", L"Armin van Burren", L"Jennifer Lopez"};

for(int i = 0; i < m_ItemsListBox.GetCount(); ++i)
{
    CString item;
    int length = m_ItemsListBox.GetTextLen(i);
    m_ItemsListBox.GetText(i, item.GetBuffer(length));
    for(int j = 0; j < sizeof(dance)/sizeof(*dance); ++j)
    {
        if(item != dance[j])
        {
            m_ItemsListBox.DeleteString(i);
        }
    }
}

I'm trying to remove from a listbox(m_ItemsListbox) all elements that are not part from the CString array. But how I coded it doesnt work, because if the first element its different it will delete it without searching the entire array.

Doesn't seemed like a hard task but I really have no idee how to do it. I think one way should be to use a CList instead of the array because it has a find() method, but I don't like it because I have to manually add all the elements, do you guys have another idee? Or the CList solution is the only one ?

Sorry, I'm a MFC begginer. Thanks for your time.


Hmmm I wouldn't be comfortable deleting things from the list box while iterating through the items in the listbox seems to be asking for problems down the line. Honestly you could do something like this, I've just whipped together - construct a list of all the item indexes you want to remove and remove them at the end.

CList<int, int> ListIndexItemsToRemove;

for(int i = 0; i < m_ItemsListBox.GetCount(); ++i)
{
    CString item;
    int length = m_ItemsListBox.GetTextLen(i);
    m_ItemsListBox.GetText(i, item.GetBuffer(length));

    bool isMatchFound = false;
    for(int j = 0; j < sizeof(dance)/sizeof(*dance); ++j)
    {
        if(item == dance[j])
        {
            isMatchFound = true;
        }
    }
    if (!isMatchFound)
         ListIndexItemsToRemove.AddHead(i);
}
for(int i = 0; i < ListIndexItemsToRemove.GetCount(); ++i)
      m_ItemsListBox.DeleteString(ListIndexItemsToRemove.GetAt(ListIndexItemsToRemove.FindIndex(i));

but - it may be better to clear the whole list and refill it everytime something changes, as Martin says (if it doesn't affect anything.


For dynamic lists I tend to store data in its own variable and clear/re-populate the list when that data changes. Especially as the list gets bigger re-adding the strings tends to be much faster than doing searches through the list and/or original source.

0

精彩评论

暂无评论...
验证码 换一张
取 消