How to Highlight (select) a line in ListView

  • Thread starter Thread starter Bob Geltz
  • Start date Start date
B

Bob Geltz

I am able to populate a ListView with several detail lines (several
columns). When finished, I would like to pre-select the first item in the
list (before the user interacts with the list). This way, if a user clicks
on the OK button, there will be a default selection. I know how to use
ListView.SelectedItems to get the selection, I just don't know how to make
an item be selected without the user actually clicking on a line.

Any suggestions? This has to be a trivial problem, but I cannot find
anything in the documentation that tells me what property to set (or how to
set it)

Thanks..
 
Try the following... I'm assuming that you're using a CListView derived
class. If not, this can be substituted for a dialog list control fairly
easily. Just make sure that the "Show selection always" property is
set if using a dialog or "from scratch" implementation.

void CListViewAppView::OnInitialUpdate()
{
CListView::OnInitialUpdate();
LVCOLUMN lvColumn = {0};

CListCtrl *ListCtrl = NULL;

ListCtrl = (CListCtrl*)&GetListCtrl();

// I know that you said you already know how to do this,
// but for the sake of the example...

lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.pszText = "Column 0";
lvColumn.cx = 100;

ListCtrl->InsertColumn(0, &lvColumn);

lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.pszText = "Column 1";
lvColumn.cx = 100;

ListCtrl->InsertColumn(1, &lvColumn);

ListCtrl->InsertItem(0, "(0, 0)");
ListCtrl->SetItemText(0, 1, "(0, 1)");

ListCtrl->InsertItem(1, "(1, 0)");
ListCtrl->SetItemText(1, 1, "(1, 1)");

ListCtrl->InsertItem(2, "(2, 0)");
ListCtrl->SetItemText(2, 1, "(2, 1)");

// Use the following to select a row.
ListCtrl->SetItemState(1, LVIS_SELECTED, LVIS_SELECTED);

// Use the following to display an entire row as selected
// should you need to do so.
ListView_SetExtendedListViewStyleEx(ListCtrl->m_hWnd,
LVS_EX_FULLROWSELECT,
LVS_EX_FULLROWSELECT);
}

I am able to populate a ListView with several detail lines (several
columns). When finished, I would like to pre-select the first item in the
list (before the user interacts with the list). This way, if a user clicks
on the OK button, there will be a default selection. I know how to use
ListView.SelectedItems to get the selection, I just don't know how to make
an item be selected without the user actually clicking on a line.
 
Back
Top