MFC: CListCtrl LVS_SORTASCENDING not working?

252 Views Asked by At

I'm not sure why something so simple doesn't seem to work? I have a CFormView with a CListCtrl member variable that uses DDX. The Dialog already has the Ascending sort option set in the resource editor, but I even force it with ModifyStyle() it still doesn't sort, my added item always ends up at the end of the list. Groups are enabled, so not sure if that's causing an issue, but basically here's what I do below. Any ideas?

// have class with the CListCtrl and DDX
class CMyView : public CFormView
{
 public:
  CListCtrl m_MyList;
};

// init the CListCtrl
void CMyView::OnInitialUpdate()
{
    __super::OnInitialUpdate();
    
    m_MyList.ModifyStyle(0, LVS_SORTASCENDING);
    
    if (m_MyList.GetHeaderCtrl()->GetItemCount()==0) {
        // add our columns
        m_MyList.InsertColumn(0, _T("The Column"), LVCFMT_LEFT, 500);
        // enable groups
        m_MyList.EnableGroupView(TRUE);
        // add our groups
        LVGROUP lvg={};
        lvg.cbSize = sizeof(lvg);
        lvg.mask = LVGF_HEADER|LVGF_GROUPID;

        lvg.pszHeader = _T("Group Header 1");
        lvg.iGroupId++;
        if (m_MyList.InsertGroup(-1, &lvg)>=0) {
            m_Group1=lvg.iGroupId;
        }

        lvg.pszHeader = _T("Group Header 2");
        lvg.iGroupId++;
        if (m_MyList.InsertGroup(-1, &lvg)>=0) {
            m_Group2=lvg.iGroupId;
        }
    }

};

// adding item ends up at the end of the list - NOT sorted
void CMyView::AddListItem(const TCHAR* str)
{
    LVITEM lvi={};
    lvi.mask|=LVIF_TEXT|LVIF_IMAGE|LVIF_PARAM|LVIF_GROUPID;
    lvi.pszText=const_cast<TCHAR*>(str);
    lvi.lParam=0;
    lvi.iImage=ICONidxSomething;
    lvi.iGroupId=m_Group1;
    lvi.iItem=m_MyList.GetItemCount();
    m_MyList.InsertItem(&lvi);
}
1

There are 1 best solutions below

1
On

According to the explanation in the official documentation.

For the LVS_SORTASCENDING and LVS_SORTDESCENDING styles, item indexes are sorted based on item text in ascending or descending order, respectively. Because the LVS_LIST and LVS_REPORT views display items in the same order as their indexes, the results of sorting are immediately visible to the user. The LVS_ICON and LVS_SMALLICON views do not use item indexes to determine the position of icons. With those views, the results of sorting are not visible to the user.

We need to set the correct List View properties.

LONG lstyle;
//Get the style of the current listctrl
lstyle = GetWindowLong(m_MyList.m_hWnd, GWL_STYLE); 
//clear display
lstyle &= ~LVS_TYPEMASK;
//set style
lstyle |= LVS_REPORT;
SetWindowLong(m_MyList.m_hWnd, GWL_STYLE, lstyle);

OR change in VS Properties window.

enter image description here