Question

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);
        }
    }
Was it helpful?

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.

OTHER TIPS

You can do it in the MouseUp event:

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

This will remove the Button you right-click on. If you want to you can add your loop and also the context menue code you didn't post. Don't leave it like this, as it is a surprising behaviour, to say the least..

You could also try

Button btn = sender as Button;
FlowLayoutPanel panel = btn.Parent as FlowLayoutPanel;
panel.Controls.Remove(btn);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top