Search code examples
c#winformsuser-controls

C# Removing dynamic created controls in a flowLayoutPanel


So the scenario is: UserControl with: 1 GroupBox inside: 2 combobox, 1 textbox, 1 richtextbox and 1 button for "remove the groupBox"

Form: 1 button(to add the groupBox) and a flowLayoutPanel

My problem: I can add as many groupBox components as I want, but when I click the button to "Remove the groupBox", in the "Form 1" if I do:

FlowLayoutPanel.Dispose()

I remove all the GroupBox components that were created, and in the userControl if I do:

GroupBox.Dispose();

It removes it but when I add another one it goes under the "One that was removed"

Here is the code I'm using:

UserControl:

private void Remove_Click(object sender, EventArgs e)
{
   removeFunction();
} 

Form 1:

Private void add_GroupBox(my class)
{
   myclass myClass = new myclass(datasource, null);
   flowLayoutPanel.Controls.add(myClass);
}


private void Remove_GroupBox()
{
   flowLayoutPanel.Controls.Clear(); // I know it removes all the groups created
   FlowLayoutPanel.Dispose(); // It does the same job

   // I just want the get the selected groupBox and dispose it or clear it
}

Solution

  • You have two options:

    First Option

    You can add a button to your User Control to dispose itself.

    this.Dispose();
    


    Second Option

    You can add a property to your form to track selected User Control.

    Form1:

    public Control SelectedItem { get; set; } = null;
    
    private void DeleteButton_Click(object sender, EventArgs e)
    {
        if (SelectedItem != null)
        {
            SelectedItem.Dispose();
        }
    }
    

    UserControl1:

    // You can use any Event you prefer (Enter, Click or etc.).
    private void GroupBox1_Enter(object sender, EventArgs e)
    {
       // First Parent is FlowLayoutPanel
       // Second Parent is your Form
       Form1 parent = this.Parent.Parent as Form1;
       if (parent != null)
       {
          parent.SelectedItem = this;
       }
    }