Archive

Posts Tagged ‘array’

How to Clear Multiple Edits Without Refering to Them One by One

December 15th, 1999 m3Rlin No comments

Let’s say you have a data entry form or a MP3 ID3 tag editor form. The user clicks the “Clear” button. The more edit controls you have the less you want to write the code to clear them :-) Well, here’s a better idea:

procedure TMainForm.btnClear(Sender: TObject);
var
  iI: Integer;
begin
  for iI := 0 to ComponentCount - 1 do
    if (Components[iI] is TEdit) then
      TEdit(Components[iI]).Clear;
end;

If you want to exclude a edit control from being cleared use this:
!!Note: The name check must be after the VCL class check.

if (Components[iI] is TEdit) and (TEdit(Components[iI].Name <> 'edDontClear')) then
  TEdit(Components[iI]).Text := '';

How to Create Control Arrays

December 15th, 1999 m3Rlin No comments

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.