【问题标题】:Adding Items to ToolStrip at RunTime在运行时将项目添加到 ToolStrip
【发布时间】:2012-05-24 17:47:11
【问题描述】:

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

所以我们要:

右键单击“John Smith”的datagridview

ContextMenu中选择“添加到收藏夹”

收藏夹ToolStripMenu 添加了一个新项目,上面写着“John Smith”

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

有什么好的开始想法吗?

【问题讨论】:

    标签: c# toolstripitem toolstripmenu


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      这很简单。 你只需要设置一个回调方法,用于所有喜欢的ToolStripMenuItem's。 在此方法中,您比较 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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-07
        • 1970-01-01
        • 2011-04-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多