Click here to Skip to main content
15,892,737 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a Tree Control where each node is associated with a LPARAM value. On a particular button click event I want to retrieve the LPARAM value. The below given code is executed more than once. so when i trying to retrieve the LPARAM value for the initial values its a garbage value.

What I have tried:

strTemp.Format(_T("%s %f %s %f"), _T("Length: "), fLength, _T("-->"), fCXLength);
m_strParamval = _T("LENG") + CXString::Format(_T("%d"), m_nMatID);
LPCTSTR pszParamVal = m_strParamval;

HTREEITEM hMatChild = m_cTreeCtrl.InsertItem(TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM,strTemp, 0, 0, 0, 0, (LPARAM)pszParamVal, m_hMatNode, TVI_LAST);




this is the coed for retrieving:

TVITEMEX item1;
item1.mask = TVIF_PARAM;
item1.hItem = m_hMatTest;


TreeView_GetItem(m_cTreeCtrl, &item1);
CString strPath1 = (LPCTSTR)item1.lParam;
Posted
Updated 21-Apr-17 0:53am

1 solution

This will never work as expected.

You are storing the string in m_strParamval. This string will be updated whenever you insert a new item. So you would always get the string for the last added item.

But more important, the LPARAM values might not point to a valid string anymore. m_strParamval is of type CString which might allocate new memory when assigning a new string that is larger than the existing content. Then the pointer returned by CString::GetString() (which is used when assigning a CString to a LPCTSTR) is not valid anymore.

If you want to store individual strings for each item you have to use allocated memory for each item and free that when items are removed and the tree is destroyed.
Example:
CString strParamval = _T("LENG") + CXString::Format(_T("%d"), m_nMatID);
TCHAR *pszParamVal = new TCHAR[strParamval.GetLength()];
_tcscpy(pszParamVal, strParamval.GetString());
Again: When doing so, don't forget to delete the memory when deleting items or destroying the tree control.
 
Share this answer
 
Comments
Member 12677926 21-Apr-17 8:40am    
it is a local pointer right. so where it should be exactly deleted??
Jochen Arndt 21-Apr-17 8:49am    
You must delete the memory when using my solution:
TCHAR *pszParam = (TCHAR*)item.lParam;
delete [] pszParam;

The above must be called when deleting an item (if you have such a function) and for all items when deleting the tree control (when closing the window that contains the control or within the destructor of the tree control if you have derived your own class).

Your m_strParamval is no longer used then and can be removed.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900