2011-05-06 60 views
0
for (int i = 0; i < client.Folders.Count; i++) 
     { 

      (ContextMenuListView.Items[1] as ToolStripMenuItem).DropDownItems.Add(client.Folders[i].Name);//add Folder to Move To 
      (ContextMenuListView.Items[2] as ToolStripMenuItem).DropDownItems.Add(client.Folders[i].Name);     
     } 

如何我得到了項目[1]或項[2]分項?如何在contextmenustrip上的子項上添加事件? C#

回答

1

ToolStripItemCollection.Add(string)(DropDownItems.Add())將返回新的ToolStripItem ...

,另一方面,所有其他的子項由ToolStripItemCollection DropDownItems

所以最簡單的方式來獲得兩個被引用創建的項目是:

(ContextMenuListView.Items[1] as ToolStripMenuItem).DropDownItems.Add(client.Folders[i].Name); 
(ContextMenuListView.Items[2] as ToolStripMenuItem).DropDownItems.Add(client.Folders[i].Name); 

將成爲:

ToolStripItem firstItem = (ContextMenuListView.Items[1] as ToolStripMenuItem).DropDownItems.Add(client.Folders[i].Name); 
ToolStripItem secondItem = (ContextMenuListView.Items[2] as ToolStripMenuItem).DropDownItems.Add(client.Folders[i].Name); 

或訪問所有子項:

foreach(ToolStripItem i in (ContextMenuListView.Items[1] as ToolStripMenuItem).DropDownItems.OfType<ToolStripItem>()) 
{ 
    //... 
} 

或訪問特定的子項:

var specificItem = (ContextMenuListView.Items[1] as ToolStripMenuItem).DropDownItems.Item[0]; 
相關問題