Fuzail
Fuzail

Reputation: 81

How to enable multiple bitbuttons?

I would like to know how to enable 10 bitbuttons via code without `bitbtn1.enable := true' for each one.

I tried this but it does not work:

for a:= 1 to 10 do
  begin
   bitbtn+inttostr(a).enabled:=true; 

   end;

How can I fix this, or is there another method?

Thank you

Upvotes: 1

Views: 167

Answers (2)

Fábio Amorim
Fábio Amorim

Reputation: 103

You can't do this bitbtn+inttostr(a).enabled:=true but you can do FindComponent('bitbtn'+inttostr(a)).enabled := true.

Though I do recommend you to put them all inside a panel and set panel.enabled := true. As it would be much faster and simple.

Upvotes: 2

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108948

There are many options.

If the buttons all have the same parent control and you want to adjust all TBitBtn child controls of this parent, you can simply iterate over the parent's child controls:

var
  i: Integer;
begin

  for i := 0 to ControlCount - 1 do
    if Controls[i] is TBitBtn then
      TBitBtn(Controls[i]).Enabled := True;

(In this case, the parent is Self assuming it exists. For instance, this could be a method in your form class. Explicitly, this is

  for i := 0 to Self.ControlCount - 1 do
    if Self.Controls[i] is TBitBtn then
      TBitBtn(Self.Controls[i]).Enabled := True;

If the parent is Panel1 instead, you do

  for i := 0 to Panel1.ControlCount - 1 do
    if Panel1.Controls[i] is TBitBtn then
      TBitBtn(Panel1.Controls[i]).Enabled := True;

)

If you only want to adjust some of these, you can for instance give them a Tag = 1 to distinguish them from other bit buttons:

var
  i: Integer;
begin

  for i := 0 to ControlCount - 1 do
    if Controls[i] is TBitBtn then
      if TBitBtn(Controls[i]).Tag = 1 then
        TBitBtn(Controls[i]).Enabled := True;

If they don't all have the same parent, it is slightly more tricky. One option is to create an array (a private field of the form class, say) with all your buttons at application startup:

private
  FButtons: TArray<TBitBtn>;

...

procedure TForm1.FormCreate(Sender: TObject);
begin
  FButtons := [BitBtn1, BitBtn2, BitBtn3];
end;

Then you can simply iterate over this one:

var
  Btn: TBitBtn;
begin
  for Btn in FButtons do
    Btn.Enabled := True;

Upvotes: 5

Related Questions