Clear Panel from a Usercontrol

Asked

Viewed 404 times

1

I’m developing an application where several Usercontrols will be shown in a Panel from the code below:

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

And remove them from this code:

panel1.Controls.Clear();

However, I am not able to insert this command from a button inside the Usercontrol. Only from the form where the Panel is

  • 1

    You need to put in a little more code. But to get the idea, you have to make the object Panel1 as public, and pass it to the Usercontrol constructor in order to access it in other objects (in this case, within userControl). Or leave this Panel1 as Static.

1 answer

1


You’ll have to catch the event from Button 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 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 within your userControl to fire, when the button is clicked. It’s a little more complicated, but I think it’s more correct. If you prefer, I do the code this other way too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.