INF: Associating Data with a List Box Entry

ID Number: Q74345

3.00

WINDOWS

Summary:

In the Microsoft Windows graphical environment, an application can use

the LB_SETITEMDATA and LB_GETITEMDATA messages to associate additional

information with each entry in a list box. These messages enable an

application to associate an arbitrary LONG value with each entry and

to retrieve that value. This article documents how an application uses

these messages.

More Information:

In this example, the application will associate a 64-byte block of

data with each list box entry. This is accomplished by allocating a

global memory block and using the LB_SETITEMDATA message to associate

the handle of the memory block with the appropriate list box item.

During list box initialization, the following code is executed for

each list box item:

if ((hLBData = GlobalAlloc(GMEM_MOVEABLE, 64)))

{

if ((lpLBData = GlobalLock(hLBData)))

{

// Store data in 64-byte block.

GlobalUnlock(hLBData);

}

}

SendMessage(hListBox, LB_SETITEMDATA, nIndex,

MAKELONG(hLBData, 0));

To retrieve the information associated with a list box entry, the

following code can be used:

if ((hLBData = LOWORD(SendMessage(hListBox, LB_GETITEMDATA,

nIndex, 0L))))

{

if ((lpLBData = GlobalLock(hLBData)))

{

// Access or manipulate the data or both.

GlobalUnlock(hLBData);

}

}

Before the application terminates, it must free the memory associated

with each list box item. The following code frees the memory

associated with one list box item:

if ((hLBData = LOWORD(SendMessage(hListBox, LB_GETITEMDATA,

nIndex, 0L))))

GlobalFree(hLBData);

These techniques can be used to associated data with an entry in a

combo box by substituting the CB_SETITEMDATA and CB_GETITEMDATA

messages.

Additional reference words: 3.00 combobox listbox