在RunTime中向ToolStrip添加项目

您好我有一个带有“collections夹”菜单的ToolStripMenu,我想在运行时在WinForms应用程序中添加子项。 我有一个datagridview,我右键单击以显示具有“添加到collections夹”选项的上下文菜单。 当该事件被触发时,我想使用datagriview中的所选行中的一些文本添加一个项目(我知道该怎么做)到这个collections夹菜单。 棘手的部分是我需要为我的newlyCreatedToolStripMenuItem_Click事件创建代码。 我将在稍后确定如何保存我的collections夹列表。

所以我们要去:

右键单击“John Smith”的datagridview

ContextMenu选择“添加到collections夹”

collections夹ToolStripMenu添加了一个新项目,内容为“John Smith”

单击“John Smith” ToopStripMenuItem触发一个操作(例如在daragridview行中选择该行等)

任何好的开始想法?

如果我理解你的话,我猜这正是你想要的:

  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(); } 

这很简单。 您只需设置一个回调方法,该方法用于所有喜欢的ToolStripMenuItem 。 在此方法中,您比较item.Textitem.Name属性并执行不同的collections方法。

 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); }