Spiga

Tag Property in Delphi

Tag is a small property that I rarely use. Until recently, that small property plays a really big role in my application.

As you know, Tag is an integer type property that you can use to… well… tag! If you’re not a big fan of array, tag can be used as an index (although not as powerful as index, but surely easier to code). As this is only a small app, so performance is not an issue.

In my app I have a table that contains 16 date fields, named Date1, Date2, …, Date16. I also have 16 labels that shows whether a certain date field is filled or not, by changing its FontStyle property.

Each labels corresponds to the each Date fields. So Label with tag 1 is used to show the Date1 field data.

Here’s the function I used to change the FontStyle of each labels:

procedure TfrmMain.SetLabels; 
var
i, j : Integer;
begin
// Iterate through 16 labels & 16 images

for i := 1 to 16 do
begin
// Find non empty date fields
if dtmMain.tblInvTracking.FieldByName('Date' +
IntToStr(i)).Value <> null then
begin
// Iterate through all components on the form

for j := 0 to ComponentCount-1 do
begin
// Sets the label's font style
if (Components[j] is TLabel) and
((Components[j] as TLabel).Tag = i) then
TLabel(Components[j]).Font.Style :=
TLabel(Components[j]).Font.Style + [fsBold];
end;
end
else
begin
for j := 0 to ComponentCount-1 do
begin
if (Components[j] is TLabel) and
((Components[j] as TLabel).Tag = i) then
TLabel(Components[j]).Font.Style :=
TLabel(Components[j]).Font.Style - [fsBold];
end;
end;
end;
end;


Prior to using the Tag, I have to find the correct object type with using the “is” reserved word

Components[j] is TLabel

And using the “as” reserved word

Components[j] as TLabel

With these two reserved words, I can be sure that only the Tag property of TLabel that I processed.