I have a form that contains 16 TCheckBox and 32 TEditBox. Every 2 TEditBox en-ability is depending of the checkBox state. so I uses this code which is too long:
//T1
procedure TOFAddForm.T1Click(Sender: TObject);
begin
Q1.Enabled:=T1.Checked;
P1.Enabled:=T1.Checked;
Q1.OnChange(Sender);
end;
.
.
.
//T16
procedure TOFAddForm.T16Click(Sender: TObject);
begin
Q16.Enabled:=T16.Checked;
P16.Enabled:=T16.Checked;
Q1.OnChange(Sender);
end;`
I used this code but nothing happen:
procedure TOFAddForm.T1Click(Sender: TObject);
var Q, P: TEdit;
begin
with Sender as TCheckBox do begin
Q.Name:='Q'+copy(Name,开发者_运维问答1,2);
P.Name:='P'+Copy(Name,1,2);
Q.Enabled:=Checked;
P.Enabled:=Checked;
end;
Q1.OnChange(Sender);
end;
thank you.
If all the checkboxes and edits are consistently named, you can add this OnClick event to all checkboxes:
procedure TOFAddForm.TClick(Sender: TObject);
var
C: TCheckBox;
Q, P: TEdit;
N: string;
begin
C := Sender as TCheckBox;
N := Copy(C.Name, 2, Length(C.Name));
Q := FindComponent('Q' + N) as TEdit;
P := FindComponent('P' + N) as TEdit;
Q.Enabled := C.Checked;
P.Enabled := C.Checked;
Q.OnChange(Sender);
end;
I suggest you store the TEdit
pointers into an array and then use the TCheckBox.Tag
property as an index into the array, eg:
var
Edits: array[0..15, 0..1] of TEdit;
procedure TOFAddForm.FormCreate(Sender: TObject);
var
K: Integer;
begin
for k := 0 to 15 do
begin
Edits[k, 0] := FindComponent('Q' + IntToStr(k+1)) as TEdit;
Edits[k, 1] := FindComponent('P' + IntToStr(k+1)) as TEdit;
(FindComponent('T' + IntToStr(k+1)) as TCheckBox).Tag := k;
end;
procedure TOFAddForm.T1Click(Sender: TObject);
begin
with Sender as TCheckBox do
begin
Edits[Tag, 0].Enabled := Checked;
Edits[Tag, 1].Enabled := Checked;
Edits[Tag, 0].OnChange(Sender);
end;
end;
I would strongly advise in cases like this to create the controls yourself. In the OnCreate event handler, call TEdit.Create(Self)
, store the object reference in a data structure you manage yourself, e.g. a dynamic array, set properties like Parent
, SetBounds
and eventhandlers, and look-up Sender
in your collection of object references (optionally depending on the value of Tag
), this is almost always more performant than using FindComponent
.
Added bonusses are you can alter the number of repeating controls easily (even make it dynamic at run-time!) and the dfm-code (which is embedded into the final executable) contains less almost-identical repeating data.
精彩评论