Author: Tomas Rutkauskas
How to create an array of buttons at runtime
Answer:
Here is a unit that creates a row of buttons and a label at run time and displays
which button is clicked on. All you need to do is start a new project, then paste
all the code below into Unit1.
1 unit Unit1;
2 3 interface4 5 uses6 SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms,
7 Dialogs, StdCtrls;
8 9 type10 TForm1 = class(TForm)
11 procedure FormCreate(Sender: TObject);
12 procedure ButtonClick(Sender: TObject);
13 private14 { Private declarations }15 public16 { Public declarations }17 end;
18 19 var20 Form1: TForm1;
21 22 implementation23 24 {$R *.DFM}25 26 const27 b = 4; {Total number of buttons to create}28 29 var30 ButtonArray: array[0..b - 1] of TButton; {Set up an array of buttons}31 MessageBox: TLabel;
32 33 procedure TForm1.FormCreate(Sender: TObject);
34 var35 loop: integer;
36 begin37 {Size the form to fit all the components in}38 ClientWidth := (b * 60) + 10;
39 ClientHeight := 65;
40 MessageBox := TLabel.Create(Self); {Create a label...}41 MessageBox.Parent := Self;
42 MessageBox.Align := alTop; {...set up it's properties...}43 MessageBox.Alignment := taCenter;
44 MessageBox.Caption := 'Press a Button';
45 for loop := 0 to b - 1 do{Now create all the buttons}46 begin47 ButtonArray[loop] := TButton.Create(Self);
48 with ButtonArray[loop] do49 begin50 Parent := self;
51 Caption := IntToStr(loop);
52 Width := 50;
53 Height := 25;
54 Top := 30;
55 Left := (loop * 60) + 10;
56 Tag := loop; {Used to tell which button is pressed}57 OnClick := ButtonClick;
58 end;
59 end;
60 end;
61 62 procedure TForm1.ButtonClick(Sender: TObject);
63 var64 t: Integer;
65 begin66 t := (Sender as TButton).Tag; {Get the button number}67 MessageBox.Caption := ' You pressed Button ' + IntToStr(t);
68 end;
69 70 end.