How to fast read and write in listview in delphi?

The Delphi TListView control is a wrapper around the Windows list view component. In its default mode of operation copies of the list data are transferred from your app to the Windows control and this is slow.

The alternative to this is known as a virtual list view in Windows terminology. Your app doesn't pass the data to the Windows control. Instead, when the control needs to display data it asks your app for just the data that is needed.

The Delphi TListView control exposes virtual list views by use of the OwnerData property. You'll have to re-write your list view code somewhat but it's really the only solution.


You just need to use your list in "virtual" mode.

  1. Put a TListBox on your form;
  2. Set the Style property to lbVirtual.
  3. Set the Count property to the number of items of your list.
  4. Then use the OnData handler to provide the text to be displayed on request:

As in this code (replace with some data from your database or a TStringList or such):

procedure TForm1.ListBox1Data(Control: TWinControl; Index: Integer;
  var Data: String);
begin
  Data := Format('Item %d',[Index+1]); // set the text to be displayed
end;

You can customize further the drawing by using lbVirtualOwnerDraw style, and you must draw items using an OnDrawItem event handler. There is some sample code in the Delphi documentation (at least under Delphi 7). ;)

In Virtual mode, you can display 50000 or 100000 items in an instantaneous way.

For storing the text, using a good old TStringList will be faster than the Items method of the TListBox, because this Items[] property will have to communicate with Windows with "slow" GDI messages for each item, whereas a TStringList will just store the text in the Delphi heap, which is usually much faster.


You can call BeginUpdate and EndUpdate on the listview to improve performance, by preventing the listview to redraw itself while updating. But this will probably not give you the boost you want. Besides, you need to know that accessing VCL controls directly from a thread is not safe unless synchronised.

I think it would be better to skip the listview and pick a 3rd party control like Virtual Tree View which is both great and free. :)

Tags:

Delphi