Home > other >  Can I refer to components using variables in Delphi?
Can I refer to components using variables in Delphi?

Time:09-18

I have many TLabels, and instead of manually changing their .Captions I'd like to do it in code. Something like

lbl[i] 

instead of manually

lbl1 := x; 
lbl2 := y;

CodePudding user response:

If you are using the IDE to create the labels then you have two choices:

  1. Use your own array:

    // in public or private
    var Labels : array [1..2] of TLabel;
    
    // in OnFormCreate or similar event
    begin
      Labels[1] := Label1;
      Labels[2] := Label2;
    end;
    
    // somewhere else
    var
      lLabel : TLabel;
    begin
      for lLabel in Labels do lLabel.Caption := 'xyz';
    end;
    
  2. Use the TForm.Control array of the Form you're currently in:

    var
      I : integer;
      lControl : TControl;
    begin
      for I := 0 to ControlCount-1 do 
      begin
        lControl := Controls [I];
        if lControl is TLabel then (lControl as TLabel).Caption := 'xxx';
      end;
    end;
    

CodePudding user response:

Thanks. Making an array of labels worked.

  • Related