2012-05-17 16 views
6

您好,我有一個ToolStripMenu,它帶有一個「收藏夾」菜單,我希望在運行時在我的WinForms應用程序中添加子項目。我有一個datagridview,我右鍵單擊以顯示具有「添加到收藏夾」選項的上下文菜單。當這個事件被觸發時,我想添加一個項目,使用從datagriview中的選定行中的一些文本(我知道該怎麼做)到這個收藏夾菜單。棘手的部分是我需要爲我的newlyCreatedToolStripMenuItem_Click事件創建代碼。我將決定如何保存我的收藏夾列表。在RunTime向ToolStrip添加項目

所以我們打算爲:

右擊datagridview一行「約翰·史密斯」

選擇「添加到收藏夾」從ContextMenu

ToolStripMenu有一個新的產品加入到它的收藏讀取「John Smith」

單擊「John Smith」ToopStripMenuItem觸發一個操作(例如在daragridview行中選擇該行等)

任何好的出發點?

回答

12

如果我理解你的權利,我想,這正是你想要什麼:

private void buttonAddFav_Click(object sender, EventArgs e) 
    { 
     ToolStripItem item = new ToolStripMenuItem(); 
     //Name that will apear on the menu 
     item.Text = "Jhon Smith"; 
     //Put in the Name property whatever neccessery to retrive your data on click event 
     item.Name = "GridViewRowID or DataKeyID"; 
     //On-Click event 
     item.Click += new EventHandler(item_Click); 
     //Add the submenu to the parent menu 
     favToolStripMenuItem.DropDownItems.Add(item); 
    } 

    void item_Click(object sender, EventArgs e) 
    { 
     throw new NotImplementedException(); 
    } 
4

這很簡單。 你只需要設置一個回調方法,用於所有最喜歡的ToolStripMenuItem。 在這種方法中,您比較item.Textitem.Name屬性並執行不同的最喜歡的方法。

private void FavoriteToolStriptem_Click(object sender, EventArgs e) { 
    ToolStripMenuItem item = sender as ToolStripMenuItem; 
    MessageBox.Show("You clicked on the menu item called " + item.Name + " shown as " + item.Text); 
} 
+0

這也是正確的,謝謝! – ikathegreat