Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I optimize this code by using SENDER?

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.

like image 639
Anïs El Haouéli Avatar asked Dec 28 '25 06:12

Anïs El Haouéli


1 Answers

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;
like image 145
GolezTrol Avatar answered Dec 30 '25 22:12

GolezTrol