Home Articles Books Downloads FAQs Tips

Q: Add items to a ListView from code at runtime.


Answer:

The ListView control provides a nice interface for adding items at design time from the IDE. However, you will usually need to fill in the ListView based on runtime information. This code snippet shows how to create ListView items and subitems from code.

    int NumEntries = 20;
    TListItem *NewEntry;
    ListView1->Items->BeginUpdate();
    ListView1->Items->Clear();
    for (int j=0; j < NumEntries; j++)
    {
        NewEntry = ListView1->Items->Add();
        NewEntry->Caption = "Item " + IntToStr(j);
        NewEntry->SubItems->Add("column 2");
        NewEntry->SubItems->Add("column 3");
        // NewEntry->ImageIndex = j;         // requires an imagelist
    }
    ListView1->Items->EndUpdate();

Note: The BeginUpdate function prevents the ListView from flickering as the items are added. Both TListBox and TListView provide a BeginUpdate function that you can call to keep the control from flashing as you manipulate the control's contents. The EndUpdate call signals that you have finished altering the control and that the control should now paint itself.

Note: Notice that you obtain the TListItem pointer by calling the Add function, rather than calling new directly.

Note: Also notice that you change the characteristics of the new item after calling the Add function.

Note: The Caption string appears next to the item's icon, and will always appear regardless of the ViewStyle setting of the ListView. The SubItems appear in separate columns when ViewStyle is set to vsReport. For other modes, the SubItems are invisible.



Copyright © 1997-2000 by Harold Howe.
All rights reserved.