Use variables for object name in Delphi

后端 未结 3 804
死守一世寂寞
死守一世寂寞 2021-01-16 13:25

I\'m trying to change the caption of many labels using regular way:

form1.label1.caption := \'1\';
form1.label2.caption := \'2\';
form1.label3.c         


        
相关标签:
3条回答
  • 2021-01-16 13:42

    If you want to change all labels on the form, you can use something like this:

    for i := 0 to Form1.ComponentCount do
      if Form1.Components[i] is TLabel then
        TLabel(Form1.Components[i]).Caption := IntToStr(i + 1);
    

    If labels are on Panel or some other container, you can limit this by replacing Form1 by eg "Form1.Panel1". You can also use eg. the tag property of components to easily select which labels you want to change.

    0 讨论(0)
  • 2021-01-16 13:57

    Create your controls dynamically. If you need to retain references to them hold those references in an array. For example, this is the general pattern.

    var
      FLabels: array of TLabel;
    ....
    SetLength(FLabels, Count);
    for i := 0 to Count-1 do
    begin
      FLabels[i] := TLabel.Create(Self);
      FLabels[i].Parent := Self;
      FLabels[i].Caption := IntToStr(i+1);
      FLabels[i].Left := 8;
      FLabels[i].Top := 8 + i*20;
    end;
    
    0 讨论(0)
  • 2021-01-16 13:57

    If you are sure you have 50 labels label1, label2 .. label50
    The solution could be like this:

    var lbl: TLabel;
    for i:=1 to 50 do
    begin
        lbl := FindComponent('Label'+IntToStr(i)) as TLabel;
        lbl.Caption := IntToStr(i);
    end;
    
    0 讨论(0)
提交回复
热议问题