c++winapimfcclistbox

Move an item up or down in a list box


I have a CListBox, and I want to have a Move Up/Move Down buttons, which move the currently selected item up or down.

Right now I think the only solution is to delete the item and then insert it the new position.

Is there a more efficient way to do it?


Solution

  • Here is a snippet I made 10 years ago. It uses delete and add to switch positions, but I think that's the only way.

    void CKnoepfeDlg::OnDown() 
    {
        int item = m_list.GetNextItem(-1,LVNI_SELECTED);
        if(item == -1) 
            return;
    
        if(item < m_list.GetItemCount() - 1)
        {
            CString name,befehl;
            name = m_list.GetItemText(item,0);
            befehl = m_list.GetItemText(item,1);
            m_list.DeleteItem(item);
            m_list.InsertItem(item + 1,name);
            m_list.SetItemText(item + 1,1,befehl);
            m_list.SetItemState(item + 1,LVNI_SELECTED,LVIS_SELECTED);
        }
    }