Mega Code Archive

 
Categories / Delphi / Ide Indy
 

Create a number of components runtime

Title: Create a number of components runtime Question: How can I create a given number of components runtime, without declaring them first? Next, how can I write event handlers to them? Answer: Well, the answer is not as hard as it may seem to. If we want to create 25 buttons, we can do it like this. procedure TForm1.FormCreate(Sender: TObject); var I: Integer; begin For I := 1 to 25 do TButton.Create(Self).Name := 'MyButton '+IntToStr(I); end; But this code will not work very well? Where should it be placed? Who's it's parent? And - how can I access it again? The answer is FindComponent(const AName: String): TComponent Since it's returning a component, we must cast it over to a TButton: The code is: procedure TForm1.FormCreate(Sender: TObject); var I: Integer; begin For I := 1 to 25 do begin TButton.Create(Self).Name := 'MyButton'+IntToStr(I); With TButton(FindComponent('MyButton'+IntToStr(I))) do begin Parent := Self; // Which is Form1 Top := I * 25 - 25; // Place the first button to the top, the next one Left := 0; // 25 px under, and so an. Height := 25; // Standard size Width := 75; // Standard end; end; end; Now the button is created, but nothing happends if you press it. Hmmm... we need an event handler! Let's write an OnClick procedure. First, declare it in the TForm's declaration: type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); procedure MyButtonClick(Sender: TObject); // Here! private { Private declarations } public { Public declarations } end; And... write it, just like you write any other handler. But, remember, this one will be invoked if you press any button! So it can be a good idea to find out which button the user pressed. procedure TForm1.MyButtonClick(Sender: TObject); begin If (Sender is TButton) then // Is it a button? ShowMessage('You pressed '+(Sender as TButton).Caption); end; To make this code run, add this code below Width := 75: OnClick := MyButtonClick;