Mega Code Archive

 
Categories / Delphi / Examples
 

Assigning property-values at runtime

Got a question from one ot my visitors recently: Question: How can I loop through and set properties of components without manually setting each component separately? Below is my solution. unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm1 = class(TForm) Shape1: TShape; Button1: TButton; Shape2: TShape; Shape3: TShape; Shape4: TShape; Shape5: TShape; Shape6: TShape; Shape7: TShape; Shape8: TShape; Shape9: TShape; Shape10: TShape; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} { QUESTION: How can I loop through and set properties of components without manually setting each component separately? I am writing a program which uses 10 TShapes. Currently, I am setting the tag and color properties of these components as follows. } procedure TForm1.Button1Click(Sender: TObject); begin Shape1.Shape:= stCircle; Shape1.Brush.Color:= clRed; Shape1.Tag:= 0; Shape2.Shape:= stCircle; Shape2.Brush.Color:= clRed; Shape2.Tag:= 1; Shape3.Shape:= stCircle; Shape3.Brush.Color:= clRed; Shape3.Tag:= 2; Shape4.Shape:= stCircle; Shape4.Brush.Color:= clRed; Shape4.Tag:= 3; Shape5.Shape:= stCircle; Shape5.Brush.Color:= clRed; Shape5.Tag:= 4; Shape6.Shape:= stCircle; Shape6.Brush.Color:= clRed; Shape6.Tag:= 5; Shape7.Shape:= stCircle; Shape7.Brush.Color:= clRed; Shape7.Tag:= 6; Shape8.Shape:= stCircle; Shape8.Brush.Color:= clRed; Shape8.Tag:= 7; Shape9.Shape:= stCircle; Shape9.Brush.Color:= clRed; Shape9.Tag:= 8; Shape10.Shape:= stCircle; Shape10.Brush.Color:= clRed; Shape10.Tag:= 9; end; { ANSWER: Here is one way to do it. This code will do just the same, with only 6 lines of code instead of 30. } procedure TForm1.Button2Click(Sender: TObject); var n: Integer; begin for n:= 1 to 10 do begin TShape(FindComponent('Shape' + IntToStr(n))).Shape:= stCircle; TShape(FindComponent('Shape' + IntToStr(n))).Brush.Color:= clRed; TShape(FindComponent('Shape' + IntToStr(n))).Tag:= n - 1; end; end; end.