SetItemState no effect to


I use a  SetItemState(0,LVIS_SELECTED, LVIS_SELECTED); to select a row in a CListCtrl.
But it seems that this do not set the state well. because while checking in:

    if ((pNMLV->uChanged & LVIF_STATE) 
        && (pNMLV->uNewState & LVNI_SELECTED))

Open in new window

the uNewState is not "LVNI_SELECTED", it is "LVNI_SELECTED" after clicking in the list. What is the flaw?

Who is Participating?
ZoppoConnect With a Mentor Commented:
Hi Ocrana,

hard to say what the problem is, could you maybe post some more relevant code here?

The only 'bug' I see is that you use LVNI_SELECTED instead of LVIS_SELECTED. The first one is intended to be used with GetNextItem, not as item state. But since both are defined to be 2 it should work anyway.

I made a little test dialog application and there it worked fine. I just created a dialog resource with a list control IDC_LIST1, added some code in OnInitDialog to fill the list and to select a list item and added a LVN_ITEMCHANGED notification handler. Here the relevant code parts:
// in header
class CTestDlg : public CDialog
	afx_msg void OnItemChanged(NMHDR* pNMHDR, LRESULT* pResult);

// in CPP file
BOOL CTestDlg::OnInitDialog()
	CListCtrl* pListCtrl = (CListCtrl*)GetDlgItem( IDC_LIST1 );
	CString strItem;
	int nIndex = 0;

	pListCtrl->InsertColumn( 0, _T( "Col 1" ), LVCFMT_LEFT, 100 );
	pListCtrl->InsertColumn( 1, _T( "Col 2" ), LVCFMT_LEFT, 100 );

	for ( int n = 0; n < 10; n++ )
		strItem.Format( _T( "Row %i" ), n + 1 );
		pListCtrl->InsertItem( n, strItem );
		strItem.Format( _T( "Subitem %i" ), n + 1 );
		pListCtrl->SetItemText( n, 1, strItem );

	pListCtrl->SetItemState( 3, LVIS_SELECTED, LVIS_SELECTED );

	return TRUE;  // return TRUE  unless you set the focus to a control

void CTestDlg::OnItemChanged(NMHDR* pNMHDR, LRESULT* pResult)

	if ( (pNMLV->uChanged & LVIF_STATE) && (pNMLV->uNewState & LVNI_SELECTED) )
		AfxMessageBox( _T( "Yep!" ) );

Open in new window

When I run this application the message box showing "Yep!" pops up immediateley (as expected) and when it's closed the 4th item is selected in the list control.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.