views:

744

answers:

2
+2  A: 

The easiest way to do this is to give Option3 a name and then check for it in a loop:

 SubItem := nil;
 for i := 0 to popdynamic.Items.Count-1 do
   if SameText(popdynamic.Items[i].Name, 'mnuOption3') then
     SubItem := popdynamic.Items[i];

 if SubItem = nil then
   begin
     SubItem := TMenuItem.Create(popDynamic);
     SubItem.Caption := 'Option 3';
     Subitem.Name := 'mnuOption3';
     popDynamic.Items.Add(SubItem);
   end;

This way your not creating a new subitem if it already exists.

skamradt
I just updated the Code
Brad
Thanks for the example code!
Brad
+1  A: 

All you need to do to create a new submenu is take your reference to the existing menu item - if it's the same everytime, just refer to the object directly, otherwise, find it somehow - and then call Add on it with the TMenuItem you want to add. I use something similar in one of my apps to recursively build a menu from an XML file.

This should serve as a very condensed version of what I'm doing.

procedure TMainForm.AddMenuItems(XMLNode: IXMLDOMNode; Parent: TMenuItem);
var
  node: IXMLNode;
  item: TMenuItem;
begin
  for i := 0 to XMLNode.childNodes.length - 1 do begin
    node := XMLNode.childNodes.item[i];
    item := NewItem(node.attributes.getNamedItem('name').nodeValue, 0, false, true, nil, 0, '');
    if node.nodeName = 'group' then begin
      Parent.Add(item);
      AddMenuItems(node, item);
    end else begin
      //You probably want to add a Tag to your items so you can tell them apart.
      item.OnClick := DynamicItemClick;
      Parent.Add(item);
    end;
  end;
end;

procedure TMainForm.LoadData;
var
  XMLNode: IXMLNode;
  //...
begin
  //Clear old dynamic items
  while Set1.Count > 0 do
    Set1.Items[0].Free;
  //Open XML file, find right XMLNode...
  AddMenuItems(XMLNode.firstChild, Set1, '');
end;

...where Set1 is the menu item I'm building menu items for. In your case, I'm guessing that would be Sub26 (and Sub23 for the one in the pop-up menu). Just use this basic approach, replacing the XML stuff with whatever you need to read your file.

Michael Madsen