Thread: Button Caption

    #1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2003
    Posts
    1
    Rep Power
    0

    Button Caption


    As someone new to delphi, I am trying to get the following loop which will number 5 buttons to work

    For x:=1 to 5 do
    begin
    button(x).caption:=x;
    end;

    Can anyone tell my why this doesn't work?
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,607
    Rep Power
    4247
    Are the components named Button1 ... Button5? You can't tell it to work on a component name like that. Besides, the subscripting array operator in Delphi is [], not (). Also, you need to convert x to string, if you want to assign it to a Caption property (use IntToStr for this). With that said, here's one way to do it (assuming that the buttons are already created by your form designer)
    Code:
    var
      button: array[1..5] of TButton;
      x : integer;
    begin
       button[1] := Button1;
       button[2] := Button2;
       button[3] := Button3;
       button[4] := Button4;
       button[5] := Button5;
    
       for  x := 1 to 5 do
         button[x].Caption := IntToStr(x);
    end;
    If you want to create buttons on the fly, here's how to do it.
    Code:
    var
       button : array[1..5] of TButton;
       x : integer;
    begin
       for  x := 1 to 5 do
       begin
         button[x] := TButton.Create(self);
         button[x].Parent := self;
         button[x].Left := (x - 1) * 100 + 10;
         button[x].Top := 20;
         button[x].Caption := IntToStr(x);
       end;
    end;
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2003
    Posts
    3
    Rep Power
    0
    Or you could do something like the following

    Code:
    var
      x: integer;
    begin
      for x := 1 to 5 do
        TButton(Self.FindComponent('Button' + IntToStr(x))).Caption := IntToStr(x);
    end;
    Obviously you would have to be sure that buttons were actually named Button1, Button2 etc.
    Last edited by pahunt; December 5th, 2003 at 07:45 AM.

IMN logo majestic logo threadwatch logo seochat tools logo