Search code examples
c#buttoncustom-controlscontextmenusender

Remove controls at run time using context menu in C#


I create a few custom controls (buttons) inside a tabControl which contains a FLP at run-time by dragging files on it. I want to remove buttons when I right click on a button and from a context menu select remove. My question is how do I know which button I right click to remove ?

How I create the button:

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

My try to remove the buttons, but is not removing the one I select..

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

Solution

  • You can first declare a method:

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

    Then modify your existing code to:

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

    Done.