Link to home
Start Free TrialLog in
Avatar of leowlf
leowlf

asked on

How to use ListCtrl's GetItem

I need to retrieve the pzsText from a listctrl item.
I only know its iItem value.  The code below i tried keep crashing.

LV_ITEM lv ;
lv.mask = LVIF_TEXT ;
lv.iItem = 10 ; // e.g. i need the pszText from item No.10
m_listCtrl.GetItem(&lv);

CString psz = lv.pszText ;

Any suggestion?
Avatar of leowlf
leowlf

ASKER

Edited text of question
ASKER CERTIFIED SOLUTION
Avatar of Answers2000
Answers2000

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Basically your code is almost right, but there's a couple of problems:

1. The main problem is it's upto you to supply the buffer pointed to by LV_ITEM (and it's size).  The reason for the crash is that you don't supply the buffer, and where-ever lv.pszText happens to get point (probably NULL) will get overwritten.

2. You really should explicity intiialize the iSubItem member of lv to 0 (or a subitem).  The compiler will not necessarily do this for you

3. It would probably also be a good idea to check the return value of GetItem

The fixed code is then
char szBuffer[256] ;
LV_ITEM lv ;
lv.mask = LVIF_TEXT ;
lv.iItem = 10 ;
lv.iSubItem = 0 ;
lv.pszText = szBuffer ;
lv.cchTextMax = sizeof szBuffer ;
CString strValue ;
if ( m_listCtrl.GetItem(&lv) )
{
   strValue = szBuffer ;
}


One final point, if you are only ever retreiving the text, have you considered using GetItemText member of CListCtrl, example:

CString strValue ;
strValue = m_listCtrl.GetItemText( 10, 0 ) ; // first param is iItem, second is iSubItem