2008. május 30., péntek

ListBox.Items.Add is slow and flickers


Problem/Question/Abstract:

ListBox.Items.Add is slow and flickers

Answer:

Adding a (larger) group of entries to a ListBox is very slow, because after every "items.add" call the ListBox is repainted.

There are two ways to overcome this:

Use the Windows message WM_SETREDRAW (see Win32.hlp for details). The VCL provides two methods for this: BeginUpdate and EndUpdate. I would assume that this is faster than solve #2.
Read the strings in a temporary TStringList object. Maybe you already have such a list - in this case you should use your existing list. Then use the Assign method to transfer the whole list.

Solve 1:

procedure TForm1.Button1Click(Sender: TObject);
var
  i: integer;
begin
  ListBox1.Items.BeginUpdate;
  for i := 1 to maxitems do
    ListBox1.Items.add(IntToStr(i));
  ListBox1.Items.EndUpate;
end;


Solve 2:

procedure TForm1.Button2Click(Sender: TObject);
var
  i: integer;
  tmp: tstringlist;
begin
  tmp := TStringList.Create;
  for i := 1 to maxitems do
    tmp.add(inttostr(i));
  ListBox1.Items.Assign(tmp);
  tmp.Free;
end;

Nincsenek megjegyzések:

Megjegyzés küldése