Board index » delphi » how can I process a series of buttons using an array index

how can I process a series of buttons using an array index

On my form I've created many buttons
button1
button2
button3
button4

I an trying to find a way to loop thru the buttons in
a FOR... loop and change the enabled property
for i := 1 to 4 do
    button[i].enabled := condition;

is this possible ?

shaun callender
sh...@rsasoftwareinc.com

 

Re:how can I process a series of buttons using an array index


In message <37CEA724.1...@rsasoftwareinc.com>, Shaun Callender stated:
Quote
> I an trying to find a way to loop thru the buttons in
> a FOR... loop and change the enabled property
> for i := 1 to 4 do
>     button[i].enabled := condition;

> is this possible ?

 for i := 0 to ComponentCount - 1 do
   if Components[i] is TButton then
     TButton(Components[i]).Enabled := condition;

the above assumes that it is being executed in a method of your form.
--
Regards
Ralph (TeamB)
--

Re:how can I process a series of buttons using an array index


Quote
> On my form I've created many buttons
> button1
> button2
> button3
> button4

> I an trying to find a way to loop thru the buttons in
> a FOR... loop and change the enabled property
> for i := 1 to 4 do
>     button[i].enabled := condition;
> is this possible ?

Yes, in a way. You can look up a component by name in its owners
component list using the owners FindComponent method, so the code
becomes (the owner is usually the form)

  for i:= 1 to 4 do
    (FindComponent('button'+IntToStr(i)) As TButton).Enabled :=
condition;

Note that an exception will result if one of the buttons is not found.

The technique above depends on a naming convention which i find highly
useless <g>. I prefer buttons to have a component Name that describes
what they do. In such a case FindCOmponent is of little use. But you
can easily build TLists or arrays the contain references for buttons
you want to handle as a group and the loop over the lists. Creating the
lists is done in the forms OnCreate event:

  FButtonList:= TList.Create;
  FButtonList.Add( EditCutButton );
  FButtonList.Add( EditCopyButton );
  FButtonList.Add( EditPasteButton );

The forms OnDestroy handler would contain a FButtonList.free;

You can now do things like

 for i:= 0 to FButtonList.Count-1 do
   TButton( FButtonlist[i] ).Enabled := condition;

Peter Below (TeamB)  100113.1...@compuserve.com)
No e-mail responses, please, unless explicitly requested!

Other Threads