Search code examples
c#buttoncustom-controlstabcontrolflowlayoutpanel

context menu to delete selected button


I create a custom control inside a tab control which contains a flowLayoutPanel on every tab by dragging files on the selected tab. I have a context menu to rename and delete tab pages, but i want also to be able to delete a button created when I right click on it and select "remove"... I cannot find a way to delete only the selected button..

This is what I have to create the buttons:

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

        foreach (string s in fileList)
        {
            var button = new Button();
            path_app = String.Format("{0}", s);
            string filename = path_app;
            file_name = Path.GetFileName(path_app);

          Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(filename);
          Bitmap bmp = icon.ToBitmap();
          CustomControl custom_btn = new CustomControl(button, new Label { Text = file_name });
          button.Tag = path_app;
          button.BackgroundImage = bmp;
          button.BackgroundImageLayout = ImageLayout.Stretch;
          FlowLayoutPanel selectedFLP = (FlowLayoutPanel)tabControl1.SelectedTab.Controls[0];
          selectedFLP.Controls.Add(custom_btn);
          button.Click += new EventHandler(button_Click);

            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 e)
    {
        foreach (Control X in fl_panel.Controls)
        {
            fl_panel.Controls.Remove(X);
        }
    }

How do I get the button which I right click on it as sender in the rmv_btn_click event to know which one to delete?


Solution

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

            Button btn = new Button();
            Label lbl = new Label();
            CustomControl cst_btn = new CustomControl(btn, lbl);
            cst_btn = sender as CustomControl;
            DialogResult dialogResult = MessageBox.Show("Are you sure that you want to remove this object?", "Remove object", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.Yes)
            {
                cst_btn.Dispose();
            }
            else if (dialogResult == DialogResult.No)
            {
                //do nothing
            }
    
    
        }
    
        public EventHandler handlerGetter(CustomControl button)
        {
            return (object sender, EventArgs e) =>
            {
                rmv_btn_click(button, e);
            };
        }