weed
weed

Reputation: 23

delphi boolean procedure for enable or disable button

I want to create a procedure to enable or disable button, can i do it with a single procedure? for example like this:

Procedure MainForm.buttonsEnabled(boolean);
BEGIN
if result=true then
begin
button1.enabled:=True;
button2.enabled:=True;
button3.enabled:=True;
end else
begin
button1.enabled:=false;
button2.enabled:=false;
button3.enabled:=false;
end;
END;

and when I call the procedure to disable or enable the button i can call it like

buttonsEnabled:=True;// to enable button
buttonsEnabled:=False;// to disable button

can I do it like that? I can't find a way to do that in the simple way

Upvotes: 0

Views: 9950

Answers (3)

Theo
Theo

Reputation: 464

For multi usage

First Option :

Procedure EnabledDisableControls(Ctrls:Array of TControl; Enabled:Boolean);
var
  C:TControl;
begin
  for C in Ctrls do
    C.Enabled:=Enabled;
end;


//calling example : 
procedure TForm1.BtnTestClick(Sender: TObject);
begin
  EnabledDisableControls([Button1, Button2, Button3], false {or True});
end;

Second Option :
Recrusivelly (or not) enabling/disabling buttons on a Control :

Procedure EnableDisableButtonsOnControl(C:TControl; Enabled:Boolean; Recrusive:Boolean);
var
  i:integer;
begin
  if C is TButton {or TBitButton or anything you need} then
    C.Enabled:=Enabled
  else if C is TWinControl then
    for i := 0 to TWinControl(C).ControlCount-1 do
    begin
      if TWinControl(C).Controls[i] is TButton then
        TButton(TWinControl(C).Controls[i]).Enabled:=Enabled
      else
      if Recrusive then
        EnableDisableButtonsOnControl(TWinControl(C).Controls[i],Enabled,true);
    end;
end;

//calling example :
procedure TForm1.BtnTestClick(Sender: TObject);
begin
  //disable all buttons on Form1:  
  EnableDisableButtonsOnControl(Self, false, false {or true});
  ...
  //disable all buttons on Panel1:  
  EnableDisableButtonsOnControl(Panel1, false, false {or true});
  ...
  //disable all buttons on Panel1 recursively:  
  EnableDisableButtonsOnControl(Panel1, false, true);
end;

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612884

Create a property of the form:

type
  TMyForm = class(TForm)
  private
    procedure SetButtonsEnabled(Value: Boolean);
  public // or private perhaps, depending on your usage
    property ButtonsEnabled: Boolean write SetButtonsEnabled;
  end;

Implement it like this:

procedure TMyForm.SetButtonsEnabled(Value: Boolean);
begin
  button1.Enabled := Value;
  button2.Enabled := Value;
  button3.Enabled := Value;
end;

And then you can use it as you intend:

ButtonsEnabled := SomeBooleanValue;

Upvotes: 5

fantaghirocco
fantaghirocco

Reputation: 4868

procedure MainForm.buttonsEnabled(AEnabled: Boolean);
begin
  button1.Enabled := AEnabled;
  button2.Enabled := AEnabled;
  button3.Enabled := AEnabled;
end;

buttonsEnabled(True);
//buttonsEnabled(False);

Upvotes: 6

Related Questions