Reputation: 2593
I have a button on a form.
The button name is bmod2
, while the form name is fLayOut1
When a user clicks the button I would like to save the name of the current form and button name
procedure TFLayout1.bMod2Click(Sender: TObject);
var
azone : string;
adept : string;
begin
azone := //forum name here
adept := //button name here
end;
Upvotes: 2
Views: 6267
Reputation: 3820
Since you're NOT building an composite component, you can also use the owner of the TButton.
procedure TFLayout1.bMod2Click(Sender: TObject);
var
azone: string;
adept: string;
btn: TButton;
begin
btn := (Sender as TButton);
adept := btn.Name;
// adept := TComponent(Sender).Name;
// adept := (Sender as TButton).Name;
azone := btn.Owner.Name;
ShowMessage('Form name: ' + azone + sLineBreak +
'Sender name: ' + adept);
end;
The IDE always make the form the Owner of all controls, not their immediate container (which it's their Parent).
Upvotes: 1
Reputation: 115
if you want the name of button's parent , above code do it for you but if you really want the form's name that contain button ( maybe the button is on a GroupBox or Panel or etc.) you can do it like this :
var
ParentClass: TWinControl;
begin
ParentClass:= Button1.Parent;
while not (ParentClass is TForm) do
ParentClass := ParentClass.Parent;
ShowMessage(Button1.Name);
ShowMessage(ParentClass.Name);
end;
Upvotes: 1
Reputation: 76693
To get name of the current form that the event method belongs to, you can access the Name
property directly or through the hidden Self
object as it's shown in the commented line of code below.
To get name of the component that has fired a certain event, in this case the OnClick
event, you can use commonly used Sender
parameter, which is (usually) the reference to the object, that caused the event to fire. Since the passed Sender
parameter is of base TObject
class type, which doesn't have the Name
property yet, you need to typecast this object to a type, that the Name
property has. It might be directly a type of the object having the event binded or, if you are not sure with it, or if there might be more component types binded to an event, you can use e.g. the common TComponent
ancestor class, which the Name
property defines (as it's shown in the commented line in the following code):
procedure TFLayout1.bMod2Click(Sender: TObject);
var
azone: string;
adept: string;
begin
azone := Name;
// azone := Self.Name;
adept := TButton(Sender).Name;
// adept := TComponent(Sender).Name;
ShowMessage('Form name: ' + azone + sLineBreak +
'Sender name: ' + adept);
end;
Upvotes: 7