Author: Tomas Rutkauskas
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:
1 2 procedure TForm1.Button1Click(Sender: TObject);
3 var4 i: integer;
5 begin6 ListBox1.Items.BeginUpdate;
7 for i := 1 to maxitems do8 ListBox1.Items.add(IntToStr(i));
9 ListBox1.Items.EndUpate;
10 end;
Solve 2:
11 12 procedure TForm1.Button2Click(Sender: TObject);
13 var14 i: integer;
15 tmp: tstringlist;
16 begin17 tmp := TStringList.Create;
18 for i := 1 to maxitems do19 tmp.add(inttostr(i));
20 ListBox1.Items.Assign(tmp);
21 tmp.Free;
22 end;