In your UserControl you have a Button that, when clicked, should remove the UserControl.
If you need to handle a List<UserControl>
, referencing the currently existing UCs, you have notify the owner of this List (a Form, here, apparently) when an UC is removed (remove means disposing of it, I assume).
A notification is usually an Event that is raised by an object. Your UserControl in this case: its internal components should not talk to the outside world directly.
In this case, add a public
event, which is raised when a Button inside the UC is clicked:
public partial class MyUserControl : UserControl
{
public delegate void ControlRemoveEventHandler(object sender, EventArgs e);
public event ControlRemoveEventHandler ControlRemoveNotify;
public MyUserControl() => InitializeComponent();
private void btnRemoveControl_Click(object sender, EventArgs e)
=> ControlRemoveNotify?.Invoke(this, e);
}
You can subscribe to this public event when an UserControl is created and added to the List<UserControl>
(this code also adds each new UserControl to a FlowLayoutPanel, at the same time).
When the UC's Button is clicked, the UC raises the ControlRemoveNotify
event. The handler of this event calls RemoveControl((MyUserControl)obj);
, which removes the UC from the List and then disposes of it.
When the UC is disposed of, it is also removed from the FlowLayoutPanel:
private List<MyUserControl> userControls = new List<MyUserControl>();
private void AddUCsToList(int howMany)
{
for (int i = 0; i < howMany; i++)
{
var uc = new MyUserControl();
void RemoveControl(object s, EventArgs e)
{
uc.ControlRemoveNotify -= RemoveControl;
userControls.Remove(uc);
uc.Dispose();
};
uc.ControlRemoveNotify += RemoveControl;
userControls.Add(uc);
flowLayoutPanel1.Controls.Add(uc);
}
}
In case you don't actually need the List<UserControl>
and instead you just need to show the UserControls inside a FlowLayoutPanel, you can remove the public event and simply call this.Dispose() in the internal handler of the Button's Click
event.
This will, as already described, also remove the UC from FlowLayoutPanel:
public partial class MyUserControl : UserControl
{
public MyUserControl() => InitializeComponent();
private void btnRemoveControl_Click(object sender, EventArgs e)
=> this.Dispose();
}
Nothing else is required:
private List<MyUserControl> userControls = new List<MyUserControl>();
private void AddUCsToList(int howMany)
{
for (int i = 0; i < howMany; i++)
{
flowLayoutPanel1.Controls.Add(new MyUserControl());
}
}