Reputation: 127
Can anybody please help me to know, what is the use of CListCtrl::GetItemData()
in MFC, VC++ ?
I went through MSDN description but it was not clear enough.
If anybody can provide a brief explanation and some example it will be really great and would help a lot.
Upvotes: 3
Views: 3635
Reputation: 66
Solution for beginners
For example, you have an int / string /struct or something else
struct foo
{
...
};
foo myData;
list.SetItemData(nItem, reinterpret_cast<DWORD_PTR>(&myData));
...
myData = *(reinterpret_cast<foo*>(list.GetItemData(nItem)));
Note that SetItemData accepts a reference to an object, the object must be global,otherwise it will be destroyed
Upvotes: 1
Reputation: 17613
The method GetItemData()
is used in association with the method SetItemData()
to allow a CListCtrl
or a CTreeCtrl
to have associated with items or nodes in the control some data.
The idea is that when populating the list or tree with nodes you can also assign a data item to the node using SetItemData()
which can be retrieved by using GetItemData()
when processing a selection event. The associated data may be something like a pointer to an object or an identifier of some sort which is the key to data stored in a collection such as a std::map
.
The data type for the value retrieved with GetItemData()
or assigned to an item with SetItemData()
is a DWORD_PTR
(see DWORD and DWORD_PTR on 64 bit machine for a discussion on DWORD_PTR
).
Another coincidence is that the SendMessage()
and PostMessage()
Windows API function have the LPARAM
parameter, e.g. SendMessage(HWND hWnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
which is the same size as a LONG_PTR
which is a long
on x32 compile or __int64
on x64 compiles (see Microsoft Docs - Windows Data Types). And a DWORD_PTR
is the same as a ULONG_PTR
which just so happens to be a unsigned long
on x32 compile or unsigned __int64
on x64 compiles.
This means that the DWORD_PTR
value from GetItemDataa()
can be used as the LPARAM
value in a SendMessage()
or PostMessage()
. So you could use the SetItemData()
method to associate a LPARAM
type of identifier that the handler for a selection event for a CListCtrl
or CTreeCtrl
can then send to some other window or thread whose handle is known to communicate the selection event to some other part of the application.
Upvotes: 3
Reputation: 50883
The item data allows you to associate any data you want to each item of your list control. This data is most of the time a pointer to some data structure.
For example in an email application you have a list control containing all received emails. Each item contains for example the sender, the subject and the date. The item data would contain a pointer to some data structure which contains the whole mail text amoung other information.
Upvotes: 5