[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 168
  • Last Modified:

Referencing a TObject using a string

How do you reference an object (TMenuItem to be specific) in code through a string variable containing the object's name?

I need this because I want to to be setting the enable properties of the menu items in my application according to the data that will be supplied by a database.
0
ziche
Asked:
ziche
1 Solution
 
kretzschmarCommented:
you can use

var
  MenuItem : TMenuItem;
begin
  menuitem := form1.findcomponent('MenuItemName') as TMenuItem;
  if assigned(MenuItem) then
    ....

meikl ;-)    
0
 
CayceCommented:
Woudn't it be easier to use the Tag property ?

Assign your TMenuItems a unique Tag value, then browse through all the TMenuItem components (use the Component and ComponentCount properties of your TForm or TMenu and then filter by the ClassName property).

PseudoCode:

function TMenuItem TForm.FindMenuItem(Tag: Integer)
begin
  Result := nil;
  for i = 1 to Form.ComponentCount
    if Form.Components[i].ClassName = "TMenuItem" then
      if Form.Components[i].Tag = LookupTag then
      begin
        Result := Form.Components[i];
        i := Form.ComponentCount;
      end;
end;
0
 
zicheAuthor Commented:
Thanks Cayce for openig my mind and reminding me of the many different ways there are for approaching problems.

This time though, I'll go with  kretzschmar's solution because of its simpler implementation.
0

Featured Post

[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now