How To Set Extra Data With Each Row Of A List Box

February 3, 2009

We can associate a 32 bit value with each row of a list box. The member function SetItemData() of CListBox can be used for this purpose.

The syntax is

int SetItemData(
   int nIndex,
   DWORD_PTR dwItemData
);

Parameters

  • nIndex – Zero based row index of the list box
  • dwItemData – 32 bit value to be stored in the row

The return value will be LB_ERR, if an error occurs.
The stored value can be retrieved using CListBox::GetItemData(). Again, the syntax is

DWORD_PTR GetItemData(
   int nIndex
) const;

where nIndex is the zero based index of the list box row, from where we have to get the data.

An example is given below.

for (int index = 0; index < myListBox->GetCount(); ++index)
{
   if (myListBox->GetItemData(index) == DWORD(-1))
   {
      myListBox->SetItemData(index, 0);
   }
}

The header file afxwin.h is needed for the above functions.