• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2185
  • Last Modified:

LB_SETITEMDATA & LB_GETITEMDATA

In windows programming, there are ListBox (or ComboBox) control messages that are 'LB_SETITEMDATA' & 'LB_GETITEMDATA'.
These messages should be very useful while adding and retrieving the strings in ListBox control window. But I only found using 'SendMessage' to add and get strings from the ListBox control window in the books. I am not very clear the usages of these messages.

Could someone show me an example of how to use the ListBox control window messages 'LB_SETITEMDATA' & 'LB_GETITEMDATA' in windows programming?

Thanks.


0
yc_yc
Asked:
yc_yc
1 Solution
 
AlexFMCommented:
Suppose you have listbox hList. The following code fragment associates string "String n" for each line in the lisbox:

int n = SendMessage(hList, LB_GETCOUNT, 0, 0);

for ( int i = 0; i < n; i++ )
{
    char* s = new char[10];
    sprintf(s, "String %d", i);
    SendMessage(hList, LB_SETITEMDATA, i, (LPARAM)s);
}

Now each item in listbox has value associated with it. This value is pointer to memory allocated on heap. The following code fragment reads these values:

int n = SendMessage(hList, LB_GETCOUNT, 0, 0);

for ( int i = 0; i < n; i++ )
{
    char* s = (char*)SendMessage(hList,  LB_GETITEMDATA, i, 0);
    // do something with s
}

Before list item is destroyed, strings should be released:

int n = SendMessage(hList, LB_GETCOUNT, 0, 0);

for ( int i = 0; i < n; i++ )
{
    char* s = (char*)SendMessage(hList, LB_GETITEMDATA, i, 0);
    delete[] s;
}

Item data may be some number or pointer. Programmer responsibility is to set, retreive and correctly release (if necessary) this data. Control just keeps this data as 32-bit value for each item. You may decide to keep any data by this way. For example, this may be some structure which is shown in dialog when user double-clicks list item.
0

Featured Post

Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now