Clear Panel from a UserControl

1

I'm developing an application where multiple UserControls will be shown in a Panel from the code below:

UserControl1 u1 = new UserControl1();
            panel1.Controls.Add(u1);

And I remove them from this code:

panel1.Controls.Clear();

However, I am not able to enter this command from a button inside the UserControl. I can only from the form where the Panel is

    
asked by anonymous 22.06.2017 / 18:17

1 answer

1

You will have to get the Button event that is inside the userControl.

In the userControl code, enter a property that returns the Button as public. So:

public Button BotaoLimpar {get{ return buttonLimpar;}} 

Now when creating the userControl, assign the event to it, like this:

 private void AddUserControl()
 {
     UserControl1 u1 = new UserControl1();
     u1.BotaoLimpar.Click += buttonLimpar_Click;
     panel1.Controls.Add(u1);
 }

 private void buttonLimpar_Click(object sender, EventArgs e)
 {
     panel1.Controls.Clear();
 }

Or, you can create an event inside your userControl to trigger when the button is clicked. It's a bit more complicated, but I think it's more correct. If you prefer, I'll code it that way too.

    
22.06.2017 / 18:38