-3

I have a string 'MyButton'.

How can I get the OBJECT MyButton from the STRING 'MyButton', so that I could write:

MyButton.Caption := 'My new Caption';

This would change the caption of the TButton MyButton object instance.

user1580348
  • 5,721
  • 4
  • 43
  • 105

1 Answers1

1

If the component has an Owner assigned (as all components placed at design-time do), then you can use the Owner's FindComponent() method, eg:

procedure TMyForm.DoSomething;
var
  Cmp: TComponent;
begin
  Cmp := Self.FindComponent('MyButton');
  if Cmp <> nil then
    (Cmp as TButton).Caption := 'My new Caption';
end;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • @user1580348: Compared to what? If you do this with GUI controls, in response to a user action, it is fine: you probably don't have millions of controls on your form, and the user is unlikely to click a million buttons per second. Still, referring to controls (and, more generally, components) by their names isn't the fastest way of doing things. Typically, one finds a different solution. But of course we don't know what your scenario is. – Andreas Rejbrand Apr 11 '20 at 23:09
  • 1
    If you want it to be quick, don't throw away the reference in the first place! – David Heffernan Apr 11 '20 at 23:10
  • If my string contains `'MyButton.Font.Size'`, how can I get the VALUE of the property `MyButton.Font.Size`? – user1580348 Apr 12 '20 at 09:19
  • @user1580348 for that, you will have to break up the string and use the substrings to [drill into the object's RTTI](http://docwiki.embarcadero.com/RADStudio/en/Working_with_RTTI) at runtime. Find the `MyButton` object, then use its RTTI to find its `Font` property and read that value to get its object, then use that object's RTTI to find its `Size` property and read its value. – Remy Lebeau Apr 12 '20 at 09:24