使用C#中的上下文菜单在运行时删除控件

时间:2014-04-04 07:54:43

标签: c# button custom-controls contextmenu sender

我在tabControl中创建了一些自定义控件(按钮),它在运行时通过拖动文件来包含FLP。我想在右键单击按钮时删除按钮,然后从上下文菜单中选择删除。我的问题是如何知道我右键单击要删除的按钮?

我如何创建按钮:

 public void tabControl1_DragDrop(object sender, DragEventArgs e)
    {
        string[] fileList = e.Data.GetData(DataFormats.FileDrop) as string[];

        foreach (string s in fileList)
        {
            var button = new Button();
            CustomControl custom_btn = new CustomControl(button, new Label { Text = file_name,  BackColor = Color.Red });
            button.Tag = path_app;

            FlowLayoutPanel selectedFLP = (FlowLayoutPanel)tabControl1.SelectedTab.Controls[0];
            selectedFLP.Controls.Add(custom_btn);

            ContextMenu cm2 = new ContextMenu();
            cm2.MenuItems.Add("Remove", new EventHandler(rmv_btn_click));
            custom_btn.ContextMenu = cm2;
        }
    }

我尝试删除按钮,但没有删除我选择的按钮..

 private void rmv_btn_click(object sender, System.EventArgs tab)
    {

        //flp_panel.Controls.Remove(sender as Button); - not working because the sender is actually the button "remove" from the context menu..
        foreach (Control X in flp_panel.Controls)
        {
            flp_panel.Controls.Remove(X);
        }
    }

3 个答案:

答案 0 :(得分:1)

您可以在MouseUp事件中执行此操作:

    private void rmv_btn__MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
            flp_panel.Controls.Remove( (Button) sender);
    }

这将删除右键单击的按钮。 如果你愿意,你可以添加你的循环以及你没有发布的上下文菜单代码。 不要这样离开它,因为这是一个令人惊讶的行为,至少可以说..

答案 1 :(得分:1)

您可以先声明一个方法:

private EventHandler handlerGetter( Button button )
{
    return ( object sender, EventArgs e ) =>
    {
        flp_panel.Controls.Remove(button); 
    };
}

然后将现有代码修改为:

cm2.MenuItems.Add("Remove", handlerGetter(custom_btn));

完成。

答案 2 :(得分:1)

您也可以尝试

Button btn = sender as Button;
FlowLayoutPanel panel = btn.Parent as FlowLayoutPanel;
panel.Controls.Remove(btn);