Search code examples
c++winapivisual-c++wtl

Can't add a column to CListViewCtrl control - WTL


I have basic dialog based window inherting from CDialogImpl in WTL:

class CMainDlg : public CDialogImpl<CMainDlg>
{
public:
    enum { IDD = IDD_MAINDLG };
    
    BEGIN_MSG_MAP_EX(CMainDlg)
        MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
        COMMAND_ID_HANDLER(ID_APP_ABOUT, OnAppAbout)
        COMMAND_ID_HANDLER(IDOK, OnOK)
        COMMAND_ID_HANDLER(IDCANCEL, OnCancel)
    END_MSG_MAP()

    LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
    LRESULT OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
    LRESULT OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
    LRESULT OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/);


protected:
    CListViewCtrl wndList1;

}

When initializing the dialog on the OnInitDialog I try to populate this List view which I created in the resource editor and named it IDC_LIST:

LRESULT CMainDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
    // center the dialog on the screen
    CenterWindow();

    // attach via CWindow ( CListViewCtrl )
    //HWND hwndList = GetDlgItem( IDC_LIST );
    wndList1.Attach( GetDlgItem( IDC_LIST ) );
    
    wndList1.InsertColumn( 0,  "Column1" , LVCFMT_LEFT, 120, 0 );


    return TRUE;
}

But even after the call to InsertColumn I see no column, I've tried the other overloads for this function which require creating a LVCOLUMNA but it didn't work either. Why is this happening?


Solution

  • If you open your resource (.rc) file in a text editor, what type of control do you see specified on the line along with IDC_LIST?

    If it is LISTBOX then you have a wrong control type. LISTBOX is for the List Box control (the CListBox class). For List Control (the CListCtrl and similar classes) the typical RC line would look like this instead:

    CONTROL "",IDC_LIST,"SysListView32",LVS_REPORT | LVS_ALIGNLEFT | WS_BORDER | WS_TABSTOP,22,14,225,64
    

    In other words, if you use Resource Editor (in Visual Studio) then be sure you select the "List Control", not the "List Box" from the set of controls offered in the toolbox. And if you want column headers, set the View property (under Appearance) to Report.

    You might also want to set the Sort property (under Behavior) to Ascending; that will apply the LVS_SORTASCENDING style to the control.