Search code examples
c++listboxselectionwxwidgets

How to clear all selections in a wxListBox (with wxLB_MULTIPLE)?


How can I clear all selections in a wxListBox which has the style wxLB_MULTIPLE?

Neither wxControlWithItems::SetSelection() nor wxControlWIthItems::SetStringSelection() work. They only select the passed item but they do not deselect any other items as said in the documentation:

Note that this does not cause any command events to be emitted nor does it deselect any other items in the controls which support multiple selections.


Solution

  • Platform independent method

    As SteveL mentioned, you have to use wxListBox::GetSelections() and wxListBox::Deselect() in a loop:

    wxArrayInt selections;
    int count = m_listBox->GetSelections(selections);
    
    for ( int i=0; i<count; i++ )
    {
      m_listBox->Deselect(selections[i]);
    }
    

    ListBox_SetSel macro for Windows systems

    You can use the macro ListBox_SetSel from the Windows API.

    For this function, you have to include Windowsx.h and wx/msw/winundef.h, of course:

    #include <Windowsx.h>
    #include <wx/msw/winundef.h>
    
    // ...
    HWND hListBox = (HWND)m_listBox->GetHandle();
    ListBox_SetSel(hListBox, false, -1);