In the android app, I'm creating some buttons (the quantity of the buttons that will be created depends on some info I'm getting from a server and it's possible to change every time I use the app, so the quantity of buttons may change). The info I'm getting, I put in 3 Memos (Memo1, Memo2 and Memo3). The Memo1 has numbers, Memo2 has names for the text property of the buttons and the Memo3 has a unique numbers who I want to use later depending on which button I clicked from those I created. The code of the Button creation is this (in form Menu).
for n := i-1 downto 0 do
begin
if Memo1.lines[n]='2' then // the buttons created only if this statement is true
begin
btnRunTime := TButton.Create(OptTab);
with btnRunTime do begin
Align := TAlignLayout.Top;
Visible := True;
Margins.Top := 5;
Height := 60;
TintColor := $FF1AB9B9;
FontColor := $FF1E1E86;
Text := Memo2.Lines[n];
Name := 'btn_' IntToStr(n);
Tag := StrToInt(Memo3.Lines[n]); // unique number
Parent := OptTab.Rectangle2;
OnClick := OptTab.CommandClick;
end;
num := num 1;
end;
end;
The buttons are creating in another form (OptTab) in a rectangle and there I use the event Commandclick which trigged when I click any of the created buttons. SO FAR SO GOOD. The problem is that when I click any button I want to use the specific Property (Tag) which I put the unique number in it.
procedure TOptTab.CommandClick(Sender: TObject);
begin
id:=IntToStr(Tag);
ShowMessage(id);
end;
When I Clicked it show me the Tag of the Form OptTab which is 0 and not the Tag of the created button I clicked. Is there a way for the app to see which button I clicked and take its Tag? (btw I check all the Memos and buttons that created and works fine and a don't use (if) to checked the texts of names in Memo2 to find the unique values because there also may change from the server) This is why I'm trying the Tag property. I appreciate any help!
CodePudding user response:
Sender
is the button pressed. Also usually better to use a local variable for id
.
procedure TOptTab.CommandClick(Sender: TObject);
begin
var id := IntToStr((Sender as TButton).Tag);
ShowMessage(id);
end;
Or if you are sure it will always be a TButton passed:
procedure TOptTab.CommandClick(Sender: TObject);
begin
var id := IntToStr(TButton(Sender).Tag);
ShowMessage(id);
end;
The first version uses RTTI to perform a safe typecast (and throws an exception if there is a problem) while the second casts without doing those checks.