Visual Basic allows programmers to create control arrays. If VB does, then how about Delphi? It sure does, but the whole idea is a bit different than in Visual Basic. You can do this to allow all controls to share a message handler (e.g. all the components can have an <i>OnClick</i> handler). For example, let’s create an array of 10 <i>TButton</i> controls:
<pre>
<b>type</b>
TForm1: <b>class</b>(Form);
…
Button1: TButton;
Button2: TButton;
…
Button10: TButton;
<b>procedure</b> FormCreate(Sender: TObject);
<b>public</b> <i>// Or “private” if you won’t use it outside this class</i>
…
aButtons: <b>array</b>[1..10] <b>of</b> TButton; <i>// In Delphi 4+ you can create dynamic arrays</i>
…
<b>end</b>;
…
<b>implementation</b>
…
<i>// In this example the array is created on program startup but it can be created anywhere</i>
<b>procedure</b> TForm1.FormCreate(Sender: TObject);
<b>begin</b>
<i>// Create the array</i>
aButtons[1] := Button1;
aButtons[2] := Button2;
…
aButtons[10] := Button10;
<b>end</b>;
</pre>
Now some examples on how to access the buttons:
<pre>
aButtons[1].Caption := ‘The first button’;
…
<i>// This code can be very usefull when a group of components has to resize when it’s parent resizes</i>
aButtons[1].Width := Form1.Width - 100;
</pre>
…and the idea on how to assign the same event handler for the controls in the array:
<pre>
<b>var</b>
iI: Integer;
…
<b>for</b> iI := 1 <b>to</b> 10 <b>do</b>
aButtons[iI].OnClick := FormOnClick;
</pre>
You don’t have to group components of one type. You can create an array of <i>TControl</i> or <i>TComponent</i>. All you have to do is type cast the controls when initializing the array.
Tags: array, control arrays, delphi 4, dynamic arrays, group components, gt class, message handler, program startup, type lt, usefull, visual basic
Merlin’s Delphi Forge
Leave a comment