7

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

所以我们要:

右键单击datagridview“John Smith”的行

选择“添加到收藏夹”ContextMenu

收藏夹ToolStripMenu中添加了一个新项目,上面写着“约翰·史密斯”

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

有什么好的开始想法吗?

4

2 回答 2

16

如果我理解正确,我想这正是您想要的:

    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();
    }
于 2012-05-17T07:43:37.277 回答
4

This is quite simple. You just have to setup a callback method which is used for all favorite ToolStripMenuItem's. In this method you compare the item.Text or item.Name attributes and execute the different favorite methods.

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);
}
于 2012-05-17T06:38:16.147 回答