Search code examples
c++user-interfacemfcdialogclistctrl

How do I select an entire row in a CListCtrlEx


What should be done in order to automatically select one of the rows in a CListCtrlEx after it has been filled with data. The purpose is to select a default row when the CListCtrlEx is displayed. For example, if the data shown is a list of cities, to show one of the cities (could be, the previously selected one), selected by default next time the control is shown.


Solution

  • Assuming m_MyList is part of a dialog, we add the following lines to OnInitDialog() and we want to select the first row:

    m_MyList.SendMessage(LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);
    m_MyList.SetItemState(0, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
    m_MyList.SetFocus();
    return FALSE;  // return TRUE  unless you set the focus to a control
    

    Don't forget to change the default

    return TRUE;
    

    to

    return FALSE;